Vue 组件之间的传值
父组件向子组件传值
props传值可以传递字符串,数组,对象…
子组件写法
1 <template>
2 <span>{{ title }}</span>
3 </template>
4 <script>
5 export default {
6 props: ['title']
7 };
8 </script>
子组件通过
props来接收父组件传递过来的值上面的
props是数组的写法,也可以写成对象的方式,可以规定父组件传递过来的值是什么类型
1 <template>
2 <span>{{ title }}</span>
3 </template>
4 <script>
5 export default {
6 props: {
7 title: String
8 }
9 };
10 </script>
父组件写法
1 <template>
2 <div>
3 <Children title='测试'></Children>
4 </div>
5 </template>
6 <script>
7 import Children from "./components/children";
8 export default {
9 components: {
10 Children
11 },
12 };
13 </script>
- 还可以动态的传值,通过
v-bind传递动态数据
1 <template>
2 <div>
3 <Children v-bind:title="test"></Children>
4 </div>
5 </template>
6 <script>
7 import Children from "./components/children";
8 export default {
9 data() {
10 return {
11 test: "测试"
12 };
13 },
14 components: {
15 Children
16 }
17 };
18 </script>
子组件向父组件传递数据
子组件主要通过事件给父组件传递消息
通过使用
$emit发射事件
子组件写法
1 <template>
2 <div>
3 <button @click="handEmit"></button>
4 </div>
5 </template>
6 <script>
7 export default {
8 data() {
9 return {
10 list: [1, 2]
11 };
12 },
13 methods: {
14 handEmit() {
15 this.?emit("pops", this.list);
16 }
17 }
18 };
19 </script>
父组件写法
1 <template>
2 <div>
3 <Children @pops="getData"></Children>
4 </div>
5 </template>
6 <script>
7 import Children from "./components/children";
8 export default {
9 data() {
10 return {
11 list: null
12 };
13 },
14 methods: {
15 //处理子组件的数据
16 getData(data) {
17 this.list = data;
18 }
19 },
20 components: {
21 Children
22 }
23 };
24 </script>
子组件之间相互传递
- 子组件与子组件没有直接的传递方法
- 可以先传递给父组件,再通过父组件传递给字组件