父組件:vue
<template> <child :name="name"></child> </template> <script> import child from "./child.vue" export default { components: {child}, data(){ return {name:"二哈"} } } </script>
子組件:git
<template> <div>{{name}}</div> </template> <script> export default { props:["name"] } </script>
父組件:github
<template> <child @childToParent="reviceSondata"></child> </template> <script> import child from "./child.vue" export default { components: {child}, methods:{ reviceSondata(data){ console.log(data); } } } </script>
子組件:vuex
<template> <button @click="dataTofather">點擊</button> </template> <script> export default { data () { return { message: '啦啦啦啦' } }, methods:{ dataTofather(){ this.$emit("childToParent",this.message,true); } } } </script>
store.js:session
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 定義狀態 state: { headImg: JSON.parse(sessionStorage.getItem('headImg')) || "" }, mutations: { newImg(state, msg){ sessionStorage.setItem('headImg', JSON.stringify(msg)) state.headImg = msg; } } }) export default store
main.js中引入vuexapp
import Vue from 'vue'; import Vuex from 'vuex'; import store from './vuex/store'; Vue.use(Vuex); var v = new Vue({ el: '#app', router, store, components: {index}, template: '<index/>', created: function () { } })
傳值:this.$store.commit("newImg", value);
取值:this.$store.state.headImg
this
github地址:vue傳值code