vuex创建store并用computed获取数据

vuex中的store是一个状态管理器,用于分发数据。相当于父组件数据传递给子组件。

1.安装vuex

npm i vuex --save

2.在src目录中创建store文件夹,里面创建store.js

(1)store.js里引入vue和Vuex,

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

(2)创建并导出store对象

export const store = new Vuex.Store({  })

(3)在store对象中创建数据

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
    state:{
        product:[
            {name:"自行车",price:120},
            {name:"电动车",price:200},
            {name:"出租车",price:300},
            {name:"大货车",price:444},
        ]
    }
})

3.在main.js中引入store

import Vue from 'vue'
import App from './App'
import {store} from '../src/store/store'    // 引入store
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,    // 这里写这里
  components: { App },
  template: '<App/>'
})

4.在子组件中使用computed获得store里的数据

<template>
<div>
    <p>one</p>
    <table border="1">
        <tr>
            <th>产品名称</th>
            <th>产品价格</th>
        </tr>
        <tr v-for="(item,i) in getProduct">
            <td>{{item.name}}</td>
            <td>${{item.price}}</td>
        </tr>
    </table>
</div>
</template>
<script>
export default {
  name: "One",
  data () {
    return {
    };
  },
  computed:{
      getProduct(){
          // this.$tore.state.xxx
          return this.$store.state.product;
      }
  }
}
</script>
<style lang="css" scoped>
table{
    width: 200px;
    height: 100px;
    border-collapse: collapse;
}
</style>

 

转载于:https://www.cnblogs.com/luguankun/p/10759638.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值