欢迎来到Cecilia陈的博客

孤独,是人一生最好的修行。

09 Vue-store仓库传参

store 存储仓库传参

  • 当我么需要访问另一条url的时候,我们可能会携带参数会访问,并且通过参数会获取到对应的数据
  • store仓库的特点:当页面一刷新,数据就没了,回到了定义时的初始值
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
	// 我们可以在这里,提前定义好一个变量值
	// 用来接收从一个url 跳到另一个url时,传过来的数据
    detail:{}
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})
<template>
        <div class="ad">
            <img :src="phone.img" alt="">
            <p class="title"><b>品牌:{{phone.title}}</b></p>
            <p>价格:{{phone.price}}</p>
            <p class='click' @click="clickEvent(phone)">详情页面-></p>
            <!--<router-link :to="'ad/detail/' + phone.id">详情页面</router-link>-->
        </div>
</template>

<script>
    import ad from '@/components/ad.vue'

    export default {
        ad,
        name: "phone",
        props: ['phone', 'id'],
        methods: {
            // 当触发这个点击事件的时候
            // 首先先去获取store创库中我们提前定义好的变量
            // 从这个组件中将数据传给store仓库中的detail变量
            clickEvent(phone) {
                // this.$store.state.detail 用来获取detail变量
                this.$store.state.detail = phone;
                // 将数据保存到store仓库中以后,在转跳路由
                this.$router.push({
                    name:'ad-detail',
                    params:{pk:phone.id}
                })
            },
        }
    }
</script>
<template>
    <div class="wrap">
        <p @click="clickEvent">返回</p>
        <div class="detail">
            <p><b>商品详情页面</b></p>
            <img :src="detail.img">
            <div class="d">
                <p>品牌:{{detail.title}}</p>
                <p>价格:{{detail.price}}</p>
                <p>出产日期:{{detail.date}}</p>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "addetail",
        data() {
            return {
                detail: {},
            }
        },
        methods: {
            clickEvent() {
                this.$router.go(-1)
            }
        },
		
        // 利用created 钩子完成数据的接收
        created() {
            window.console.log(this.$store.state.detail);
            // this.$store.state.detail;可以获取到store仓库中的数据
            this.detail = this.$store.state.detail;
        },
    }
</script>
posted @ 2019-11-23 18:44  Cecilia陈  阅读(506)  评论(0编辑  收藏  举报