Vue3 使用vuex 系统常量的两种方法

目录:

方式一:创建store/index.js
方式二:创建store/index.js和store/modules/index.js
安装vuex
# 使用 npm 安装
npm install vuex@next --save

# 或使用 yarn 安装
yarn add vuex@next

# 或使用 pnpm 安装
pnpm add vuex@next
## 
在 main.js 中注册 Vuex
#// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)
app.mount('#app')

方式一.创建store/index.js

// src/store/index.js
import { createStore } from 'vuex'

export default createStore({
  state: {
    index: {
      dataObj: {} // 初始数据
    }
  },
  mutations: {
    // 直接设置整个 dataObj
    setDataObj(state, newData) {
      state.index.dataObj = newData
    },
    
    // 或者只修改 dataObj 的某个属性
    updateDataObjProperty(state, { key, value }) {
      state.index.dataObj[key] = value
    }
  },
  actions: {
    // 异步更新
    updateDataObj({ commit }, newData) {
      // 这里可以有异步操作
      commit('setDataObj', newData)
    }
  },
  getters: {
    getDataObj: state => state.index.dataObj
  }
})

第一种:Vue 3 的 < script >语法在index.vue中

import { ref, onMounted, onUnmounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

export default {
  setup() {
    const store = useStore()
    const dataObj = computed(() => {
      return store.state.index.dataObj
    })
    // 或者使用 getter
    // const dataObj = computed(() => store.getters.getDataObj)
	// 点击按钮 重新赋值
	const saveData = () => {
		store.commit('saveDataObj', '2222');
	};
    return {
      dataObj,
      Search
    }
  }
}

第二种:Vue 3 的 < script setup >语法 获取值,赋值

<template>
  <div>
    <p>当前数据: {{ dataObj }}</p>
    <button @click="updateData">更新数据</button>
     <button @click="saveData">赋值数据</button>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

const store = useStore()
const dataObj = computed(() => store.state.index.dataObj)
// 点击按钮 重新赋值
const saveData = () => {
	store.commit('saveDataObj', '2222');
};

// 读取数据(通过 getter)
const dataObj = computed(() => store.getters.getDataObj)

// 修改数据 - 通过 mutation
const updateData = () => {
  const newData = { name: '新数据', value: '新值' }
  store.commit('setDataObj', newData)
}

// 或者通过 action(如果有异步操作)
const updateDataAsync = () => {
  const newData = { name: '新数据', value: '新值' }
  store.dispatch('updateDataObj', newData)
}
</script>
#// 完全替换 dataObj
store.commit('setDataObj', { 
  id: 1, 
  name: '新名称', 
  items: ['a', 'b', 'c'] 
})
#// 只修改特定属性
store.commit('updateDataObjProperty', { 
  key: 'name', 
  value: '修改后的名称' 
})

#// 添加新属性到 dataObj
store.commit('updateDataObjProperty', { 
  key: 'newField', 
  value: '新字段的值' 
})

二.创建store/index.js和store/modules/index.js

1.store/index.js


import { createStore } from 'vuex';
import index from './modules/index';
 
const store = createStore({
  modules: {
    index
  }
});
 
export default store;

2.store/modules/index.js

const state = {
    dataObj: '123'
};
const mutations = {
  saveDataObj(state, obj) {
    state.dataObj = obj;
  }
}; 
export default {
  state,
  mutations
};

1. 第一种

<template>
	<section class="module">
		<span class="title" @click="saveData">标题{{dataObj}}</span>
	</section>
</template>
<script>
	import {	ref, onMounted, 	computed 	} from 'vue';
	import {	useStore } from 'vuex';
	export default {
		setup() {
			const store = useStore();
			const dataObj= computed(() => {
				 return store.state.index.dataObj;	 
			});
			// 点击按钮 更改从store获取的数据
			const saveData = () => {
			 	store.commit('saveDataObj', '2222');
			};
         return {
				saveData 
				dataObj
			};
		}
	};
</script>

2. 第二种

<script>
	
	import {useStore} from 'vuex';
	export default {
		data() {
			return {
				dataObj:'',
			};
		},
		computed:{
			key(){
				this.dataObj= this.$store.state.index.dataObj;
			}
		},

		methods: {
			handleLogin(type) {
			 	console.log("dataObj",this.dataObj)			
			},	
		}
	};
</script>
<think>在Vue 3中,使用`defineComponent`定义的组件,如果需要在模板中使用导入的常量,有几种方法可以实现: 1. **直接在`setup()`函数中返回常量**:这是最常用的方式。在组件的`setup()`函数中,你可以导入常量,然后将其返回,这样它就会成为模板上下文的一部分,可以在模板中直接使用。 2. **使用`computed`属性**:如果常量需要根据某些响应式数据进行计算,或者你想将其作为一个计算属性,可以使用`computed`。 3. **通过`provide/inject`**:如果常量需要在多个嵌套组件中使用,可以通过`provide`在父组件中提供常量,然后在子组件中通过`inject`来注入。 4. **使用全局属性**:如果常量在整个应用中都使用,可以考虑将其挂载到app的全局属性上(使用`app.config.globalProperties`),然后在组件中通过`this`访问(在选项式API中)或通过`getCurrentInstance()`来访问(在组合式API中)。但这种方法不推荐用于常量,因为它会使全局属性变得臃肿,而且难以维护。 5. **使用Vuex或Pinia**:如果常量是全局状态的一部分,可以将其放在状态管理中。 这里我们主要讨论第一种方法,因为它是最直接且常用的。 ### 示例代码 假设我们有一个常量文件`constants.js`: ```javascript // constants.js export const MAX_ITEMS = 10; export const APP_NAME = &#39;My Vue App&#39;; ``` 现在,在Vue组件中导入这些常量并在模板中使用: ```vue <template> <div> <h1>Welcome to {{ appName }}</h1> <p>You can add up to {{ maxItems }} items.</p> </div> </template> <script> import { defineComponent } from &#39;vue&#39;; import { MAX_ITEMS, APP_NAME } from &#39;./constants&#39;; export default defineComponent({ setup() { // 直接返回常量,以便在模板中使用 return { maxItems: MAX_ITEMS, appName: APP_NAME }; } }); </script> ``` ### 解释 - 在`setup()`函数中,我们导入了两个常量:`MAX_ITEMS`和`APP_NAME`。 - 然后,我们在`setup()`返回的对象中,将这两个常量作为属性返回。这样,它们在模板中就可以像组件的其他响应式数据一样被使用。 - 在模板中,我们使用双大括号语法`{{ }}`来绑定这些常量。 ### 注意 - 这些常量是静态的,不会改变,因此不需要使用`ref`或`reactive`来包装它们。 - 如果常量是一个对象或数组,并且你不打算修改它,那么直接返回即可。但是,如果你需要在模板中绑定一个常量对象或数组的属性,并且希望这些绑定是响应式的,那么你可能需要使用`reactive`或`ref`来包装。但通常,常量是不变的,所以直接使用即可。 ### 另一种方式:在`<script setup>`语法糖中使用 如果你使用Composition API和`<script setup>`语法糖,那么更简单: ```vue <template> <div> <h1>Welcome to {{ APP_NAME }}</h1> <p>You can add up to {{ MAX_ITEMS }} items.</p> </div> </template> <script setup> import { MAX_ITEMS, APP_NAME } from &#39;./constants&#39;; </script> ``` 在`<script setup>`中,所有顶层绑定(包括导入的变量)都会自动暴露给模板,无需返回。 ### 相关问题 §§相关问题§§: 1.Vue 3的`setup()`函数中,如何定义响应式数据? 2. Vue 3的Composition API中,`<script setup>`语法糖是什么?它有什么优势? 3.Vue组件中,如何使用全局常量(比如配置信息)? 4. Vue 3中,如何通过`provide`和`inject`在组件树中共享常量? </think>在 Vue 3使用 `defineComponent` 定义的组件时,在模板中使用导入的常量有几种常见方法。以下是详细的解决方案和代码示例: ### 解决方案:三种常用方法 #### 方法1:在 `setup()` 中返回常量(推荐) ```vue <script> import { defineComponent } from &#39;vue&#39;; // 导入常量 export const MAX_ITEMS = 10; export default defineComponent({ setup() { // 直接在setup中返回常量 return { MAX_ITEMS // 暴露给模板使用 }; } }); </script> <template> <div>最大数量: {{ MAX_ITEMS }}</div> </template> ``` **解释**: - 在 `setup()` 函数中返回常量,使其成为模板上下文的一部分 - 模板中直接通过 `{{ 常量名 }}` 使用 - **优点**:简单直接,支持 TypeScript 类型推断 #### 方法2:使用 `computed` 包装常量(需要响应式时) ```vue <script> import { defineComponent, computed } from &#39;vue&#39;; export const API_URL = &#39;https://api.example.com&#39;; export default defineComponent({ setup() { // 使用computed包装常量(当需要响应式特性时) const apiUrl = computed(() => API_URL); return { apiUrl }; } }); </script> <template> <div>接口地址: {{ apiUrl }}</div> </template> ``` #### 方法3:在选项式 API 的 `data` 中声明 ```vue <script> import { defineComponent } from &#39;vue&#39;; export const DEFAULT_COLOR = &#39;#42b983&#39;; export default defineComponent({ data() { return { // 在data中重新声明常量 DEFAULT_COLOR }; } }); </script> <template> <div :style="{ color: DEFAULT_COLOR }">主题色文本</div> </template> ``` ### 关键注意事项: 1. **模板只能访问显式暴露的变量**:必须通过 `setup()` 返回或在 `data`/`computed` 中声明 2. **常量命名规范**:推荐使用全大写+下划线的命名方式(如 `MAX_ITEMS`) 3. **响应性需求**: - 如果常量永远不会改变,直接返回即可 - 如果后续可能变为响应式数据,使用 `ref` 或 `computed` 包装 4. **模块作用域**:导入的常量默认是模块局部变量,需显式暴露给模板 ### 最佳实践建议 ```vue <script> import { defineComponent } from &#39;vue&#39;; // 常量集中管理文件 constants.js import { MAX_ITEMS, API_ENDPOINT, COLOR_PRIMARY } from &#39;@/constants&#39;; export default defineComponent({ setup() { // 一次性暴露所有需要的常量 return { MAX_ITEMS, API_ENDPOINT, COLOR_PRIMARY }; } }); </script> <template> <div> <p>限制: {{ MAX_ITEMS }} 条</p> <a :href="API_ENDPOINT">访问API</a> <button :style="{ background: COLOR_PRIMARY }">提交</button> </div> </template> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云端信息咨询

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值