1. vue中各个组件之间传值

1.父子组件

父组件-->子组件,通过子组件的自定义属性:props

子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);

2.非父子组件或父子组件

通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)

3.非父子组件或父子组件

更好的方式是在vue中使用vuex

方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。

方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据

2. Vuex

官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),

让其在各个页面上实现数据的共享包括状态,并且可操作

Vuex分成五个部分:

1.State:单一状态树

2.Getters:状态获取

3.Mutations:触发同步事件

4.Actions:提交mutation,可以包含异步操作

5.Module:将vuex进行分模块

3. vuex使用步骤

3.1 安装

npm install vuex -S

安装完成后 package.json中会有

"vuex": "^3.1.1"

3.2 创建store模块,分别维护state/actions/mutations/getters

3.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations' Vue.use(Vuex) const store = new Vuex.Store({
state,
getters,
actions,
mutations
}) export default store

3.4 在main.js中导入并使用store实例

import store from './store'
new Vue({
el: '#app',
data() {
return {
/* 总线*/
Bus:new Vue({ })
}
},
router,
store,
components: {
App
},
template: '<App/>'
})

4. vuex的核心概念:store、state、getters、mutations、actions

4.0 store

每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。

const store = new Vuex.Store({

state,    // 共同维护的一个状态,state里面可以是很多个全局状态

getters,  // 获取数据并渲染

actions,  // 数据的异步操作

mutations  // 处理数据的唯一途径,state的改变或赋值只能在这里

})

4.1 state.js(保存数据的容器)

export default {
resturantName: '飞歌餐馆'
}

4.2 getters.js(getXxx)

export default {
getResturantName: (state) => {
return state.resturantName;
}
}

注1:getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问

this.$store.getters.resturantName

注2:state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:

computed: {

resturantName: function() {

return this.$store.getters.resturantName;

}

}

4.3 mutations(setXxx)

export default {
// type(事件类型): 其值为setResturantName
// payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName;
}
}

4.4 actions.js

export default {
setResturantNameAsync: (context, payload) => {
console.log('xxx')
setTimeout(() => {
console.log('yyy')
context.commit('setResturantName', payload); //Action提交的是mutation
}, 3000);
console.log('zzz')
},
doAjax: (context, payload) => {
//在vuex里面是不能使用vue实例的
let _this =payload._this;
let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
_this.axios.post(url, {}).then((response) => {
console.log('doAjax...........');
console.log(response);
}).catch(function(error) {
console.log(error);
});
}
}

Action类似于 mutation,不同在于:

1.Action提交的是mutation,而不是直接变更状态

2.Action可以包含任意异步操作

3.Action的回调函数接收一个 context 上下文参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性

但是他们并不是同一个实例,context 包含:

1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性

所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

实例 VuexPage1.vue

<template>
<div>
<h3 style="margin: 60px;">第一个vuex页面:{{title}}</h3>
<button @click="changeTitle">餐馆易主</button>
<button @click="changeTitleAsync">两个月后餐馆易主</button>
<button @click="doAjax">测试vuex中使用ajax</button>
</div>
</template> <script>
export default{
data() {
return { };
},
methods:{
changeTitle(){
this.$store.commit('setResturantName',{
resturantName:'小猪砍刀羊肉馆'
});
},
changeTitleAsync(){
/* 异步*/
this.$store.dispatch('setResturantNameAsync',{
resturantName:'小猪砍刀蛇肉馆'
});
},
doAjax(){
this.$store.dispatch('doAjax',{
_this:this
});
}
},
/* 计算属性*/
computed:{
title(){
// return this.$store.state.resturantName;
return this.$store.getters.getResturantName
}
}
}
</script> <style> </style>

VuexPage2.vue

<template>
<div>
<h3 style="margin: 60px;">第二个vuex页面:{{title}}</h3>
</div>
</template> <script>
export default{
data() {
return {
title:''
};
},
/* 钩子函数*/
created(){
this.title = this.$store.state.resturantName;
}
}
</script> <style> </style>

将组件挂上

import VuexPage1 from '@/views/sys/VuexPage1'
import VuexPage2 from '@/views/sys/VuexPage2'
{
path: '/sys/VuexPage1',
name: 'VuexPage1',
component: VuexPage1
},
{
path: '/sys/VuexPage2',
name: 'VuexPage2',
component: VuexPage2
}

效果:

Vuex的同步异步存值取值的更多相关文章

  1. Jmeter的JDBC Request,sql参数化及返回值取值

    1.JDBC Request面板 Variable Name:数据库连接池的名字,需要与JDBC Connection Configuration的Variable Name Bound Pool名字 ...

  2. dedecms--自定义session存值取值

    最近在用用dedecms开发项目,开发项目中遇到需要通过session存储信息在其他页面调取使用,但是对dedecms里面自带的session存储使用不好,我需要存储的是用户登录的时候信息,于是我就使 ...

  3. 【记录】【java】反射设值取值

    1.设值 /** * 根据属性名设置属性值 * * @param fieldName * @param object * @return */ public boolean setFieldValue ...

  4. localStorage存值取值以及存取JSON,以及基于html5 localStorage的购物车

    localStorage.setItem("key","value");//存储变量名为key,值为value的变量 localStorage.key = &q ...

  5. sessionStorage二种存值取值的方法

    //方法一 sessionStorage.setItem('id1','这是一个测试id1'); //存入一个值key:value console.log(sessionStorage.getItem ...

  6. Wrapped的返回值取值

    Bared   Wrapped   using Newtonsoft.Json; using Newtonsoft.Json.Linq; string str = JsonConvert.Serial ...

  7. 关联实现下-jsonpath取值(有难度!!耗时长)

    re的使用参考:正则表达式基础及re模块:https://www.cnblogs.com/dream66/p/12953729.html import restr1 = '{"access_ ...

  8. 用JQUERY为INPUT的TXT类型赋值及取值操作

    注意和纯JS操作的区别,一个是对象,一个是字串,如下说明: 在Jquery中,用$("#id")来获得页面的input元素,其相当于document.getElementById( ...

  9. Bs4 BeautifulSoup取值

    原文网址:https://blog.csdn.net/u010244522/article/details/79627073 从网页获取HTML数据后,获取对应标签.属性的值 取值方法主要有以下几种: ...

随机推荐

  1. javascript获取焦点对象ID

    document.activeElement 方法:if(document.activeElement.id="textbox1") { }

  2. 用QT写的简单Todo记事本-附源码(浮动窗口)

    去年边学边写了搞了很久, 已经好久没继续开发了, 先放出来供大家参考吧. 发现自己的学习能力还是不错的. 技术点: 使用QT, QML技术 代码参考: https://github.com/cnscu ...

  3. Dapr 客户端 搭配 WebApiClientCore 玩耍服务调用

    使用Dapr 客户端 处理服务调用,需要遵循的他的模式,通常代码是这个样子的: var client = DaprClient.CreateInvokeHttpClient(appId: " ...

  4. NTP\rsync+inotify

    NTP网络时间协议 NTP(Network Time Protocol)网络时间协议基于UDP,用于网络时间同步的协议,使网络中的计算机时钟同步到UTC(世界统一时间),再配合各个时区的偏移调整就能实 ...

  5. 基于Unity的A星寻路算法(绝对简单完整版本)

    前言 在上一篇文章,介绍了网格地图的实现方式,基于该文章,我们来实现一个A星寻路的算法,最终实现的效果为: 项目源码已上传Github:AStarNavigate 在阅读本篇文章,如果你对于里面提到的 ...

  6. 基于ScheduledExecutorService的并发定时任务处理能力测试

    测试代码 定时器类 package business.util; import java.util.concurrent.Executors; import java.util.concurrent. ...

  7. DVWA(三):SQL injection 全等级SQL注入

    (本文不定期更新) 一.所需环境: 1.DVWA 2.web环境 phpstudy/wamp 3.burp suite 二.SQL注入产生的原因: 程序员在编写代码的时候,没有对用户输入数据的合法性进 ...

  8. Innodb中怎么查看锁信息

    一.前言 上一篇说了下innodb中锁的大概意思, 这篇说说怎么查看加的哪些锁.不然后续出现死锁或者锁等待都不知道为什么. 二.底层基础表信息 在学会如何查看有哪些锁信息时, 需要了解一些基础表信息, ...

  9. S3C2440—12.按键中断

    文章目录 一. 总体 二. CPSR设置 三. 中断源设置 四. 中断控制器设置 五. C中断处理函数 六. 汇编IRQ异常处理程序 七. 源码 一. 总体 要驱动按键中断控制LED亮灭,程序要进行如 ...

  10. 题解 P3643 [APIO2016]划艇

    题解 一种思路很好想:\(f_{i,j}\) 表示前 \(i\) 所学校中,第 \(i\) 所学校参赛且派出 \(j\) 艘划艇的方案数.(转移就不列了.) 这种方式有一个致命点,就是 \(j\) 的 ...