Vue组件化和路由

组件化
组件化是vue的核心思想,它能提高开发效率,方便重复使用,简化调试步骤,提升整个项目的可维护性,便于多人协同开发
组件通信
父组件 => 子组件:
属性props
特性$attrs
引用refs

// child
props: { msg: String }
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>


// child:并未在props中声明foo<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>


// parent
<HelloWorld ref="hw"/>
mounted() {
this.$refs.hw.xx = 'xxx'
}

子元素$children

// parent
this.$children[0].xx = 'xxx'

子元素不保证顺序
子组件 => 父组件:自定义事件
// child
this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>
兄弟组件:通过共同祖辈组件
通过共同的祖辈组件搭桥,$parent$root
// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')
祖先和后代之间
// ancestor
provide() {
return {foo: 'foo'}
}
// descendant
inject: ['foo']
由于嵌套层数过多,传递props不切实际,vue提供了 provide/inject API完成该任务provide/inject:能够实现祖先给后代传值
任意两个组件之间:事件总线 或 vuex事件总线:创建一个Bus类负责事件派发、监听和回调管理
export default class Bus{
    constructor(){
        this.callbacks = {}
    }
    $on(namefn){
        this.callbacks[name= this.callbacks[name|| []
        this.callbacks[name].push(fn)
    }
    $emit(nameargs){
        if(this.callbacks[name]){
            this.callbacks[name].forEach(cb => cb(args))
        }
    }
}
// main.js
Vue.prototype.$bus = new Bus()
// child1
this.$bus.$on('foo', handle)
// child2
this.$bus.$emit('foo')
实践中可以用Vue代替Bus,因为它已经实现了相应功能vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更
插槽
插槽语法是Vue 实现的内容分发 API,用于复合组件开发。该技术在通用组件库开发中有大量应用。匿名插槽
具名插槽
将内容分发到子组件指定位置

// comp1
<div>
<slot></slot>
</div>
// parent
<comp>hello</comp>

作用域插槽
分发内容要用到子组件中的数据

// comp3
<div>
<slot
:foo="foo"></slot>
</div>
// parent
<Comp3>
<!-- v-slot的值指定为作用域上下文对象 --><template v-slot:default="slotProps">
来自子组件数据:{{slotProps.foo}}</template>
</Comp3>

Vue-router
Vue-router是vue.js官方路由管理器,它和vue.js的核心深度集成,让构建单页面变得易如反掌
安装: vue add router
核心步骤:
步骤一:使用vue-router插件,router.js
import Router from 'vue-router'
Vue.use(Router)
步骤二:创建Router实例,router.js
export default new Router({…})
步骤三:在根组件上添加该实例,main.js
import router from './router'
new Vue({
  router,
}).$mount("#app);
步骤四:添加路由视图,App.vue
<router-view></router-view>
导航

<router-link to="/">Home</router-link>
<router-link
to="/about">About</router-link>

原文地址:https://www.cnblogs.com/yayaxuping/p/11800830.html