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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM