2018-09-19 Vue 第八天

2018-09-25  本文已影响0人  三年_3

1.路由

路由:vue-router
是Vue的工具库 vue-router.js
下载:
npm install vue 下载vue
npm install vue-router 下载vue-router

        通过不同的url访问不同的页面
               spa(single page application)  单页面应用

···
<div id="star">

<router-link to='/home'>首页</router-link>
<router-link to='/detail'>详情页</router-link>

<router-view></router-view>
</div>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script>
//2.创建组件
var Home={
template:<h1>这是首页</h1>
}

    var Detail={
        template:`
            <h1>这是详情页</h1>
        `
    }
    
    //3.配置路由
    var routes=[
        {path:'/home',component:Home},
        {path:'/detail',component:Detail}
    ]
    
    //4.创建一个路由实例
    const router=new VueRouter({
        routes:routes
    })
    
    //5.把路由挂在到vue实例上
    new Vue({
        el:'#star',
        router:router
    })
</script>

···

2. 生命周期

···
<div id='app'>{{msg}}</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#app',
data:{
msg:'hello vue'
},
beforeCreate:function(){
alert('beforeCreate')
},
created:function(){
alert('Created')
},
beforeMount:function(){
alert('befroeMounted')
},
mounted:function(){
alert('mounted')
}
})
</script>
···

3.非父子组件之间的通信

<div id="app">
<child></child>
<son></son>

</div>
<script src="js/vue.js"></script>
<script>
    //同级别相传  child 发送   son  接收
    var bus=new Vue();
    Vue.component('child',{
        template:`
           <div>
             <h2>我是child组件</h2>
             <button @click='sendMsg'>发送数据</button>
           </div>  
        `,
        data:function(){
            return{
                msg:'我是child组件中的数据,要传给son组件'
            }
        },
        methods:{
            sendMsg:function(){ //发送数据
               bus.$emit('send',this.msg) 
            }
        }
    })
    
    
    //设置 函数 用来接收
    
    Vue.component('son',{
        template:`
           <div>
            <h2>我是son组件</h2>
            <a>{{mess}}</a>
          </div>   
       `,
        data:function(){
            return{
                mess:''
            }
        },
        mounted:function(){
            bus.$on('send',msg=>{
                console.log(this);    
                    this.mess=msg
                    
                    })
        }
    })
    
    
    new Vue({
        el:'#app'
    })
</script>

···

上一篇 下一篇

猜你喜欢

热点阅读