// 父組件 <template> <center-template :form='userinfo'></center-template> </template> <script> import CenterTemplate from '../../components/admin/userCenterTemplate' export default { components: { 'center-template': CenterTemplate }, data () { return { userinfo: {name: 'jack'} } }, } </script> // 子組件 export default { props: { // 接收 form: { type: Object, default: { name: '', } } }, }
// 子元素 <el-input @input="changeInput" class="search-input" v-model="serachValue" placeholder="請輸入搜索內容"></el-input> changeInput(){ // 子元素調用父元素的方法1 if(this.$parent.nullSerarchResult){ // 新增標籤 this.$parent.nullSerarchResult() } }, // 父元素 <v-search></v-search> nullSerarchResult(val){ this.pageNum = 1 this.init({ searchKey: val }) },
// 子元素 <el-button @click="addNewFun" size='small' class="search-btn" type="primary">新增</el-button> addNewFun(){ // 第三種方式是發佈給父元素 this.$emit('addTagFun') } // 父元素 <v-search @addTagFun='addTagFun' ></v-search> addTagFun(){ this.$router.push('/admin/add_blog') },
// 子元素 <el-button @click="searchResultChild" size='small' class="search-btn" type="primary">搜索</el-button> props: { searchResult: { type: Function, default: null } }, searchResultChild(){ // 調用方法2,這種須要再props中聲明 if(this.searchResult){ this.searchResult(this.serachValue) } }, // 父元素 <v-search :searchResult='searchResult' ></v-search> searchResult(val){ this.pageNum = 1 this.init({ searchKey: val }) },
// common/bus.js import Vue from 'vue'; // 使用 Event Bus const bus = new Vue(); export default bus; // 組件1(接收通知信號) import bus from '@/common/bus.js' export default{ data(){ return { collapseData: '' } }, created() { // 監聽collapse,有變更就會收到通知,並改變collapseData值 bus.$on('collapse', msg => { this.collapseData = msg }) } } // 組件2 發佈信號 import bus from '@/common/bus.js' export default { methods: { sendData(){ // 發佈信號,觸發這個函數,其餘的接收函數都會收到相應的信息 bus.$emit('collapse', '信息') } } }
// store/index.js import Vue from 'vue' import Vuex from 'vuex'; Vue.use(Vuex) const store = new Vuex.Store({ state: { userinfo: {}, }, mutations: { 'SET_ROLES':(state,userinfo) => { state.userinfo = userinfo }, }, actions: { getUser({commit, state},userinfo){ commit('SET_ROLES',userinfo) }, } }) export default store // views/slider.vue import { mapState, mapAcions } from 'vuex' export default{ computed: { // 解構賦值 ...mapState({ userinfo: state => state.userinfo }) }, methods: { ...mapActions({ getUser: 'getUser' }), handleUserInfo(){ // 調用 this.$store.dispatch('getUser','對象') } } }
github地址vue
網站地址git