vue组件传值

1.父传子 prop

在父组件的子组件标签上绑定一个属性,挂在要传输的变量
<template>
  <div class="father">
    <h1>父组件</h1>
    <Son :toSon="msg"></Son>
  </div>
</template>

<script>
import Son from "./Son";
export default {
  components: {
    Son,
  },
  data() {
    return {
      msg: "父传子",
    };
  },
};
</script>
在子组件中通过props来接收数据,props可以是一个数组也可以是一个对象,接收过来的数据可以直接使用
<template>
  <div class="son">
    <h1>子组件</h1>
    <p>这是从父组件接收的值:{{ toSon }}</p>
  </div>
</template>

<script>
export default {
  //   props: ["toSon"],
  props: {
    toSon: {
      require: true,
      type: String,
    },
  },
};
</script>

2.子传父 $emit( )

在父组件组件的标签上自定义一个事件,调用相应的方法
<template>
  <div class="father">
    <h1>父组件</h1>
    <p>这是从子组件接收的值:{{ SonMsg }}</p>
    <Son :toSon="msg" @getSon="getSon"></Son>
  </div>
</template>

<script>
import Son from "./Son";
export default {
  components: {
    Son,
  },
  data() {
    return {
      msg: "父传子",
      SonMsg: "",
    };
  },
  methods: {
    getSon(val) {
      this.SonMsg = val;
    },
  },
};
</script>
在子组件的方法中通过this.$emit(‘事件名’)来触发在父组件中定义的事件,数据是以参数的形式进行传递的
<template>
  <div class="son">
    <h1>子组件</h1>
    <p>这是从父组件接收的值:{{ toSon }}</p>
    <button @click="$emit('getSon', msg)">点击这里将消息传递给父组件</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "子传父",
    };
  },
  props: ["toSon"],
};
</script>

3. 兄弟组件传值 EventBus

在main.js中,创建一个vue实例,并挂载到vue原型上
import Vue from 'vue'
import App from './App.vue'

const Bus = new Vue()
Vue.prototype.Bus = Bus
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')
在传输数据的组件中,通过Bus.$emit(‘事件名’,‘参数’)来派发事件
<template>
  <div class="son">
    <h1>子组件</h1>
    <p>这是从父组件接收的值:{{ toSon }}</p>
    <button @click="$emit('getSon', msg)">点击这里将消息传递给父组件</button>
    <button @click="toSon2">点击这里将消息传递给子组件2</button>
  </div>
</template>

<script>
export default {
  props: ["toSon"],
  data() {
    return {
      msg: "子传父",
      msg2: "兄弟传值",
    };
  },
  methods: {
    toSon2() {
      this.Bus.$emit("toBro", this.msg2);
    },
  },
};
</script>
在接收数据的组件中,通过Bus.$on(‘事件名’,(val)=>{})来接受数据
<template>
  <div class="son2">
    <h1>子组件2</h1>
    <p>这是从兄弟组件接收的值:{{ msg }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "",
    };
  },
  mounted() {
    this.Bus.$on("toBro", (val) => {
      this.msg = val;
    });
  },
};
</script>

4. vuex

vuex是一个专门为vue.js打造的状态管理模式,它相当于一个公共仓库,所有组件都使用里面的属性和方法
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    msg: 'vuex组件通信'
  },
  mutations: {},
  actions: {},
  getters: {},
  modules: {}
})
父组件
<template>
  <div class="father">
    <h1>父组件</h1>
    <p>这是从store获取的值:{{ this.$store.state.msg }}</p>
    <Son></Son>
    <Son2></Son2>
  </div>
</template>
子组件
<template>
  <div class="son">
    <h1>子组件</h1>
    <p>这是从store获取的值:{{ this.$store.state.msg }}</p>
  </div>
</template>

4. 本地存储

原理同vuex相似,利用 window.sessionStorage.setItem(“变量名”, 变量) 存储变量到本地存储,然后通过window.sessionStorage.getItem(“变量名”, 变量) 获取变量

sessionStorage传值

sessionStorage 是浏览器的全局对象,存在它里面的数据会在页面关闭时清除 。运用这个特性,我们可以在所有页面共享一份数据。

语法:
// 保存数据到 sessionStorage
sessionStorage.setItem(‘key’, ‘value’);

// 从 sessionStorage 获取数据
let data = sessionStorage.getItem('key');

// 从 sessionStorage 删除保存的数据
sessionStorage.removeItem('key');

// 从 sessionStorage 删除所有保存的数据
sessionStorage.clear();
注意:里面存的是键值对,只能是字符串类型,如果要存对象的话,需要使用 let objStr = JSON.stringify(obj) 转成字符串然后再存储(使用的时候 let obj = JSON.parse(objStr) 解析为对象)。
这样存对象是不是很麻烦呢,推荐一个库 good-storage ,它封装了sessionStorage ,可以直接用它的API存对象
// localStorage
 storage.set(key,val) 
 storage.get(key, def)
 
 // sessionStorage
 storage.session.set(key, val)
 storage.session.get(key, val)

5. Vue全局变量

原理是将属性值挂载到vue的原型上,然后通过 this.属性值 来访问变量
在main.js中写入
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'

Vue.config.productionTip = false
Vue.prototype.msg = "Vue全局变量"

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')
父组件
<template>
  <div class="father">
    <h1>父组件</h1>
    <p>这是Vue全局变量获取的值:{{ msg }}</p>
    <Son></Son>
    <Son2></Son2>
  </div>
</template>
子组件
<template>
  <div class="son">
    <h1>子组件</h1>
    <p>这是Vue全局变量获取的值:{{ msg }}</p>
  </div>
</template>

6. 路由传参

主要利用路由之间的跳转来传值
<template>
  <div>
    <h1>{{ msg }}</h1>
    <button @click="routerTo">click here to news page</button>
  </div>
</template>
 
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    routerTo(){
      this.$router.push({ name: 'news', params: { userId: 123 }});
    }
  }\
}
</script>

使用$ref传值

通过$ref的能力,给子组件定义一个ID,父组件通过这个ID可以直接访问子组件里面的方法和属性
首先定义一个子组件Children.vue
<template>
    <section>
        传过来的消息:{{msg}}
    </section>
</template>

<script>
    export default {
        name: "Children",
        components: {},
        data() {
            return {
                msg: '',
                desc:'The use of ref'
            }
        },
        methods:{
            // 父组件可以调用这个方法传入msg
            updateMsg(msg){
                this.msg = msg
            }
        },
    }
</script>
然后在父组件Parent.vue中引用Children.vue,并定义ref属性
<template>
    <div class="parent">
        <!-- 给子组件设置一个ID ref="children" -->
        <Children ref="children"></Children>
        <div @click="pushMsg">push message</div>
    </div>
</template>

<script>
    import Children from '../components/Children'

    export default {
        name: 'parent',
        components: {
            Children,
        },
        methods:{
            pushMsg(){
                // 通过这个ID可以访问子组件的方法
                this.$refs.children.updateMsg('Have you received the clothes?')
                // 也可以访问子组件的属性
                console.log('children props:',this.$refs.children.desc)
            }
        },
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值