From 0 to explore vue- componentized - pass values between the components

understanding

Vue has a very important core idea is that the components and component design to code reuse

What are the components of

Component-based, like a mainframe computer's motherboard, there is a socket memory, hard disk, CD-ROM, etc. jacks, our projects, like a mainframe computer, through the various components of the module (hard disk, memory, etc.) to fight the synthesis of a complete computer.
vue componentization
As shown, each block is a component, split by the many components together, it can be infinitely nested down

Component-based benefits

  1. Module reuse, improve efficiency, so that duplication of code written only once.
  2. Reserved for personalized settings, can ensure that the module, both universal, and variable.
  3. Improve maintainability, if a plurality of pages use the same program component (e.g., a message box shells), if the modified block playing style, only to modify the module.

Writing

cli mode

Component parts

<template>
  <div></div>
</template>
<script>
export default {
    name:"myAlert"
};
<style></style>

User part

<template>
  <div>
    <myAlert></myAlert> <!-- 实例中使用组件 -->
  </div>
</template>

<script>
import myAlert from '@/components/alert.vue';//导入自己写的组件
export default {
  components:{myAlert}//在这个vue实例中注册组件
};
</script>
<style></style>

Introduced vue.js mode

// 定义名为 todo-item 的新组件
Vue.component('myAlert', {
  template: '<div>这是一个弹框</div>'
})

var app = new Vue(...)

html partially used

<div>
    <myAlert></myAlert>
</div>

Components by value

VueScheme pass values ​​between the components present in the following

Parent => Child

props

Subassembly declaration props, to the corresponding parent componentsprops值中传递

$refs

Parent component uses this.$refs.组件名.变量the content to select sub-assemblies and sub-assemblies modification

$children

Father component uses this.$children[0].变量to select and modify the contents of sub-assemblies

Note that: a . $ Children vm official website that

$ Children does not guarantee the order, nor is it a response type

It is generally not recommended to use this method to pass by value, because it can not find a stable specified component instance, unless the page is only a sub-assembly

Further, in this embodiment, this.$children[0]it is not responsive to this.$children[0].变量the response type.

Sub => Parent

$emit

Here观察者模式

  1. Child component calls this.$emit('confirm','点击了确定')to dispatch confirman event
  2. Parent components <myAlert @confirm='successCallback'></myAlert>to listen for events;
    Note: here is, who is who monitor the distribution, that is to say, confirmthe event dispatchers and listener are myAlertcomponents, myAlertcall the parent component of the component listener after completion successCallbackcallback event, of course, 监听的事件名and 触发的事件名all 可以自定义of.

Pass each component value brothers

Use common node bypass

  1. Use common parent assembly $parentsor$root
//组件一
this.$parents.$on('foo',(e)=>{
    console.log(e);//此处e为$emit时传入的值
})
//组件二
this.$parents.$emit('foo','bar');//控制台输出bar
  1. Use pass by value between any two components of the program Click here

Cross-generational transfer value

The concept, called inter-generational transfer value, that is,

Grandparents -> parents -> child generation -> grandchildren -> ...
where collapse is more a generational or cross-generational transfer of generational values, for example, grandparents and grandchildren

provide/inject

Since the multi-level nested, the use of propstransfer is clearly unrealistic

In view of this situation, vueproviding provide/injecttwo APIto get this done

  1. Grandparents use provideto declare a variable
  2. Grandchildren use injectvariables to inject ancestors declared

Writing:

//祖辈
export default {
    provide(){//此处可以传入动态变量,与data类似
        return {
            componentYeye:this
        }
    },
    data(){
        return {
            yeyedeBianliang:'爷爷的变量'
        }
    }
}
//孙辈
export default {
    inject:['componentYeye'],//此处为数组,注入祖辈声明的变量
    mounted(){
        console.log(this.componentYeye.yeyedeBianliang);//爷爷的变量
    }
}

note

  1. This method is mostly used when making use of component library.
  2. This method is not recommended to modify the data directly grandparents grandchildren. Because these data may be used in multiple sub-assemblies, if you want to modify, you should call the grandparents component variables ways to modify, and vuexmodify variables are suggested by commitsimilar

Use pass by value between any two components of the program Click here

Pass a value between any two components

Mount prototype

The so-called prototype mount, that is, main.jspublic variables in the events, are hanging on a prototype to Vue

//main.js
Vue.prototype.$globalData = {}
Vue.prototype.$sayName = function(e){
    console.log('我的名字是',e)
}
new Vue({...})

//组件一
Vue.prototype.$globalData.name='小明';
this.$sayName('小王');//我的名字是小王

//组件二
console.log(this.$sayName.name);//小明
this.$sayName('小王');//我的名字是小王

Event Bus

The so-called event bus, that is, the current Vueoutside the instance, and then create a Vue instance to specifically variable transmission, event handling, management callback events

//main.js中
Vue.prototype.$bus = new Vue();
new Vue({...})

//组件一
this.$bus.$on('sayName',(e)=>{
    console.log('我的名字是',e)
})
//组件二
this.$bus.$emit('sayName','小明');//我的名字是 小明

vuex

VuexIt is Vuea method of providing, designed to manage vuethe public status, events, etc. See more from 0 begun to explore vue- common variable management

Guess you like

Origin www.cnblogs.com/mr-xiao-han/p/12391290.html