父传子
首先:建一个父组件 和一个子组件
父组件:
<template> <div> <div class="one-box">父组件 <div class=""> <Child :parent_msg="parent_msg"/> <!-- 子组件标签绑定父组件的数据 --> </div> </div> </div> </template> <script> import Child from '../components/Child.vue' export default { name:'Parent', data(){ return{ parent_msg:'我是父组件' } }, components:{ Child } } </script>
子组件:
<template> <div> <div class="two-box"> 子组件 <div> 父组件传过来的参数:{{parent_msg}} </div> </div> </div> </template> <script> export default { name:'Child', props:['parent_msg'] // parent_msg是从父组件里面获取过来的,名称要和父组件绑定的名称一致 } </script>
子传父
子组件
<template> <div> <div class="two-box">子组件 <button @click="setDate">子组件向父组件传值</button> </div> </div> </template> <script> export default { name:'Child', data(){ return{ child_msg:'我是子组件' } }, methods:{ setDate(){ this.$emit('getDate',this.child_msg) } // 子组件通过this.$emit触发父组件的自定义方法getdate,并把this.child_msg传递过去 } } </script>
父组件
<template> <div> <div class="one-box"> <Child @getDate="parentGetDate"/> 父组件:<div>从子组件传过来的值:{{parent_msg}}</div> </div> </div> <!-- 父组件监听到子组件触发了getDate方法后,就开始执行parentGetDate方法 ,并把子组件传递过来的数据传给date --> </template> <script> import Child from '../components/Child.vue' export default { name:'Parent', data(){ return{ parent_msg:'' } }, components:{ Child }, methods:{ parentGetDate(date){ this.parent_msg=date console.log(date) } } } </script>
兄弟组件
第一种:可以借助父组件进行传值
第二种:通过vuex实现页面传值
1、先安装 vuex npm i vuex -save
2、新建store.js文件
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //增加一个常量 const state={ count:1 } //定义mutations,处理状态的改变 const mutations={ add(state){ ++state.count }, reduce(state){ --state.count } } //向外暴露store export default new Vuex.Store({ state, mutations })
3、在main.js中导入store.js文件
4、在组件中引入store,并在export default写入store
子组件2
<template> <div> <div> 子组件2{{this.$store.store.count}} 获取state中的count值 </div> </div> </template> <script> import store from '../store/store' export default { name:'Child2', data(){ return{ } }, store, } </script> <style> </style>
子组件1:
<template> <div> <div class="two-box"> 子组件1 <button @click="$store.commit('add')">让组件2的值增加</button> <button @click="$store.commit('reduce')">让组件1的值减少</button> <!-- 调用在mutations定义的方法 --> </div> </div> </template> <script> import store from '../store/store' export default { name:'Child1', data(){ return{ } }, store } </script> <style> </style>
第三种:可以用外部文件传值