vuex创建store并用computed获取数据

Posted on   猫头唔食鱼  阅读(7637)  评论(0编辑  收藏  举报

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>
复制代码

 

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示