非父組件
<div class="box">
<first></first>
<second></second>
</div>
<script src="js/vue.js"></script>
<script>
var sent = new Vue()//中間量
Vue.component("first",{
template:`
<div>
<h1>這是first組件</h1>
<button @click='add'>傳送數(shù)據(jù)</button>
</div>
`,
data:function(){
return{
msg:'hello vue'
}
},
methods:{
add:function(){
sent.$emit("sentMsg",this.msg)
}
}
})
Vue.component("second",{
template:`
<div>
<h1>這是second組件</h1>
<p>{{mess}}</p>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){//因為mounted是vue的生命周期兢仰,所以用箭頭函數(shù)用this指向組件
sent.$on("sentMsg",msg=>{
this.mess = msg
})
}
})
new Vue({
el:'.box'
})
</script>
組件嵌套
<div id="app">
<router-link to='/home'>首頁</router-link>
<router-link to='/user'>用戶頁</router-link>
<router-view></router-view>
</div>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script>
var Home={
template:<h1>這是首頁</h1>
}
var User={
template:<div> <h1>這是用戶頁</h1> <ul> <li> <router-link to='/user/regist'>注冊</router-link> </li> <li> <router-link to='/user/login'>登錄</router-link> </li> </ul> <router-view></router-view> </div>
}
var Regist={
template:<h3>這是注冊頁</h3>
}
var Login={
template:<h3>這是登錄頁</h3>
}
//3配置路由
const routes=[
{path:'/',component:Home},
{path:'/home',component:Home},
{
path:'/user',component:User,
children:[
{path:'regist',component:Regist},
{path:'login',component:Login}
]
}
]
//4.創(chuàng)建一個路有實咧
const router=new VueRouter({
routes:routes
})
//5.
new Vue({
el:'#app',
router:router
})
</script>