Vuex的this.$store.commit和在Vue项目中引用公共方法

Posted wang-sai-sai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vuex的this.$store.commit和在Vue项目中引用公共方法相关的知识,希望对你有一定的参考价值。

 

1、在Vue项目中引用公共方法

作为一个新人小白,在使用vue的过程中,难免会遇到很多的问题,比如某个方法在很多组件中都能用的上,如果在每个组件上都去引用一次的话,会比较麻烦,增加代码量。怎么做比较好呢,话不多说直接看代码把

首先 要在main.js中引入公共js。然后,将方法赋在Vue的原型链上。像图中这样。

 技术图片
然后在需要的组件上去引入这个方法

mouted ()
//调用方法
this.common.login();


/**然后公共方法里写一段简单的代码*/
export default
login:function()
console.log(‘这是一段代码‘)

2、Vuex中的this.$store.commit

众所周知,在vue的项目里父子组件间可以用props 或者 $emit 等方式 进行数据传递,而如果项目稍微大一点的话有很多平行组件,这个时候在这些组件间传递数据,使用这些方法会比较麻烦,代码也会变得不利于服用。

我们可以vuex来解决这个问题
vuex其实官网上不是太好理解,可以直接看看代码怎么实现的。

首先还是要先安装vuex
可以创建一个单独的store文件目录,里面专门存放相关的文件
然后新建index.js文件。

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

const store = new Vuex.Store(
  state: 
    // 初始化全局的一个变量
    testTxt: "tips":"这是一条vuex的数据","id":1
  
)
export default store

然后在main.js/main.ts 中注册store

import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
import store from ‘./../store/index‘

/* eslint-disable no-new */
new Vue(
  el: ‘#app‘,
  router,
  store,
  template: ‘<App/>‘,
  components:  App 
)

接下来在组件中使用

export default 
  ...
  data()
	  value : "这又是修改后的value",
	,
  computed: 
    getTxt() 
      return this.$store.state.testTxt.tips;
    
  ,
   methods: 
    modifyTxt: function() 
      this.$store.commit(‘modifyTips‘, this.value)
    
  
  ...

然后在index.js文件里可以修改

	const store = new Vuex.Store(
		  state: 
		   	   // 初始化全局的一个变量
		   	   testTxt: "tips":"这是一条vuex的数据","id":1
		  ,
		   mutations: 
			    modifyTips(state,msg) 
			      state.testTxt.tips= msg;
			    
		  
)
export default store

 

当然了,vuex的版本肯定是越新越好

以上是关于Vuex的this.$store.commit和在Vue项目中引用公共方法的主要内容,如果未能解决你的问题,请参考以下文章

vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

vuex应用实例-this.$store.commit()触发

VUEX中的dispatch()和commit()

Vue--vuex状态管理-多界面状态管理$store.state.变量名称 ---数据通触发事件改变this.$store.commit

vuex直接修改state 与 用dispatch/commit来修改state的差异

vuex 中的 dispatch 和 commit 的使用