这里不过多说其他的,仅仅只用两个组件来说明(涉及项目中的文件结构问题就不作参考)
- 父组件的名字:App
- 父组件的template:
<template><divid="app"><h3>
{{info}}</h3><h3>
{{counter}}</h3><button@click="subClick()">-</button><button@click="addClick()">+</button><h3>HellowVuex</h3><!-- 父组件向子组件中传递数据需要动态绑定一个自定义的属性一般和父组件同名--><HellowVuexv-bind:counter="counter"></HellowVuex></div></template>
- 父组件的script:
<script>// 这里导入子组件(忽略项目结构)import HellowVuexfrom'./components/HellowVuex'exportdefault{
name:'App组件',// 注册组件
components:{
HellowVuex},// 父组件数据data(){return{
info:"app",
counter:0}},// 父组件的方法 这里绑定在button按钮中
methods:{subClick(){this.counter++},addClick(){this.counter--}}}</script>
下面是子组件:
- 子组件的名字:App
- 子组件的template:
<template><div><h3>
{{counter}}</h3></div></template>
- 子组件的script:
<script>exportdefault{
name:"HellowVuex",
props:{
counter:Number}}</script>
流程:
- 定义父组件
- 定义子组件,并在父组件中导入子组件,注册,
- 在父组件中定义相关数据,并在父组件的template标签内使用子组件