3.组件的通信
(1)ref给元素或组件注册引用信息
(2)$parent/$children 访问父子实例
(3) provide/inject(非响应式)
// A.vueexport default { provide: { name: 'Aresn' }}// B.vueexport default { inject: ['name'], mounted () { console.log(this.name); // Aresn }}
使用provide/inject代替vueapp.vue
{ { app.userInfo }}
然后可以可以使用混合mixins,将不同逻辑分开到不同js文件再注册app
(4)还是使用vuex好了哈哈...
(5)dispatch/broadcast(vue 1.x) 感觉不好用放弃
(6)自定义函数(其实就是通过一个递归函数)
// 由一个组件,向上找到最近的指定组件function findComponentUpward (context, componentName) { let parent = context.$parent let name = parent.$options.name while (parent && (!name || [componentName].indexOf(name) < 0)) { parent = parent.$parent if (parent) name = parent.$options.name } return parent}export { findComponentUpward}// 由一个组件,向上找到所有的指定组件function findComponentsUpward (context, componentName) { let parents = [] const parent = context.$parent if (parent) { if (parent.$options.name === componentName) parents.push(parent) return parents.concat(findComponentsUpward(parent, componentName)) } else { return [] }}export { findComponentsUpward}// 由一个组件,向下找到最近的指定组件function findComponentDownward (context, componentName) { const childrens = context.$children let children = null if (childrens.length) { for (const child of childrens) { const name = child.$options.name if (name === componentName) { children = child break } else { children = findComponentDownward(child, componentName) if (children) break } } } return children}export { findComponentDownward}// 由一个组件,找到指定组件的兄弟组件function findBrothersComponents (context, componentName, exceptMe = true) { let res = context.$parent.$children.filter(item => { return item.$options.name === componentName }) let index = res.findIndex(item => item._uid === context._uid) if (exceptMe) res.splice(index, 1) return res}export { findBrothersComponents}
举个例子
child.vueimport { findComponentUpward } from '../utils/assist.js'export default { mounted () { const parent = findComponentUpward(this, 'father') if (parent) { parent.sayHello() } }}
father.vue export default { name: 'father', data () { return { name: 'fater' } }, methods: { sayHello () { console.log('Hello, Vue.js') } }, mounted () { }}