[TOC]
一、介绍 :artificial_satellite:
Vue 只关注视图层, 采用自底向上增量开发的设计。
Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。
VUE是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。
二、快速入门 :artificial_satellite:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://juejin.cn/post/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
{{ message }} {{name}}
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
name : "Vue"
}
});
</script>
</body>
</html>
复制代码
三、VUE安装 :v:
1.NodeJs安装和环境配置
下载NodeJs二进制可执行程序后,逐步安装即可。
2.npm安装方式
# 查看版本
$ npm -v
2.3.0
npm install -g cnpm --registry=https://registry.npm.taobao.org
#升级 npm
cnpm install npm -g
# 升级或安装 cnpm
npm install cnpm -g
# 最新稳定版
$ cnpm install vue
复制代码
3.vue-cli命令快速构建项目
创建项目命令:
vue create hello-world
复制代码
# 全局安装 vue-cli
$ cnpm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 这里需要进行一些配置,默认回车即可
This will install Vue 2.x version of the template.
For Vue 1.x use: vue init webpack#1.0 my-project
? Project name my-project
? Project description A Vue.js project
? Author runoob <test@runoob.com>
? Vue build standalone
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Setup unit tests with Karma + Mocha? Yes
? Setup e2e tests with Nightwatch? Yes
vue-cli · Generated "my-project".
To get started:
cd my-project
npm install
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
复制代码
进入项目,安装并运行:
$ cd my-project
$ cnpm install
$ cnpm run dev
DONE Compiled successfully in 4388ms
> Listening at http://localhost:8080
复制代码
4.vue-ui 创建项目
先安装VUE-cli
cnpm i @vue/cli -g
# 安装包管理器
cnpm i yarn -g
复制代码
之后执行
vue ui
复制代码
TIPS:如果你遇到了使用 npm 安 装node_modules 总是提示报错:报错: npm resource busy or locked…..。
可以先删除以前安装的 node_modules
npm cache clean
npm install
复制代码
四、项目结构 :articulated_lorry:
目录/文件 | 说明 |
---|---|
build | 项目构建(webpack)相关代码 |
config | 配置目录,包括端口号等。我们初学可以使用默认的。 |
node_modules | npm 加载的项目依赖模块 |
src | 这里是我们要开发的目录,基本上要做的事情都在这个目录里。里面包含了几个目录及文 assets: 放置一些图片,如logo等。components:目录里面放了一个组件文件,可以不用。 App.vue: 项目入口文件,我们也可以直接将组件写这里,而不使用 components 目录。 main.js: 项目的核心文件。 |
static | 静态资源目录,如图片、字体等。 |
test | 初始测试目录,可删除 |
.xxxx文件 | 这些是一些配置文件,包括语法配置,git配置等。 |
index.html | 首页入口文件,你可以添加一些 meta 信息或统计代码啥的。 |
package.json | 项目配置文件。 |
README.md | 项目的说明文档,markdown 格式 |
五、VUE生命周期 :baby_chick:
1.beforeCreate
-
类型:Function
-
详细:
在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。
2.created
- 详细:
在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前尚不可用。
3.beforeMount
- 详细:
在挂载开始之前被调用:相关的 render 函数首次被调用。
该钩子在服务器端渲染期间不被调用。
4.mounted
- 详细:
实例被挂载后调用,这时 el 被新创建的 vm.el也在文档内。
注意 mounted 不会保证所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,可以在 mounted 内部使用 vm.$nextTick:
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
复制代码
该钩子在服务器端渲染期间不被调用。
5.beforeUpdate
- 详细:
数据更新时调用,发生在虚拟 DOM 打补丁之前。这里适合在更新之前访问现有的 DOM,比如手动移除已添加的事件监听器。
该钩子在服务器端渲染期间不被调用,因为只有初次渲染会在服务端进行。
6.updated
- 详细:
由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。
当这个钩子被调用时,组件 DOM 已经更新,所以你现在可以执行依赖于 DOM 的操作。然而在大多数情况下,你应该避免在此期间更改状态。如果要相应状态改变,通常最好使用计算属性或 watcher 取而代之。
注意 updated 不会保证所有的子组件也都一起被重绘。如果你希望等到整个视图都重绘完毕,可以在 updated 里使用 vm.$nextTick:
updated: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been re-rendered
})
}
复制代码
该钩子在服务器端渲染期间不被调用。
生命周期实例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://juejin.cn/post/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
{{msg}}
</div>
<script type="text/javascript">
var vm = new Vue({
el : "#app",
data : {
msg : "hi vue",
},
//在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。
beforeCreate:function(){
console.log('beforeCreate');
},
/* 在实例创建完成后被立即调用。
在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。
然而,挂载阶段还没开始,$el 属性目前不可见。 */
created :function(){
console.log('created');
},
//在挂载开始之前被调用:相关的渲染函数首次被调用
beforeMount : function(){
console.log('beforeMount');
},
//el 被新创建的 vm.$el 替换, 挂在成功
mounted : function(){
console.log('mounted');
},
//数据更新时调用
beforeUpdate : function(){
console.log('beforeUpdate');
},
//组件 DOM 已经更新, 组件更新完毕
updated : function(){
console.log('updated');
}
});
setTimeout(function(){
vm.msg = "change ......";
}, 3000);
</script>
</body>
</html>
复制代码
六、Docker安装Nginx :sunflower:
1.创建Nginx配置文件
#创建配置挂载文件夹目录
$ mkdir -p /home/nginx/{conf,logs}
复制代码
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
## 代理vue静态页面
server {
listen 1920;
server_name localhost;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://localhost:3003;
}
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
复制代码
2.安装nginx
## 拉取镜像
$ docker pull nginx
# 运行容器
docker run -d --name nginx -p 80:80 -v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /home/nginx/logs:/var/log/nginx nginx
复制代码
七、VUE基础知识:biking_woman:
1.要点整理
1.data 为什么要用方法而不是一个对象
因为vue是单页面应用,是由多个组件组成的,每个组件里面都有data,如果data是个对象,对象是引用类型,一个组件里面的data值改变了,其他组件的值也都会改变,为了避免出现互相引用的问题,我们要用方法来初始化数据形成一个作用域,防止各个组件互相引用
复制代码
2.VUE 的数据驱动和双向绑定
v-model:双向绑定
v-cloak:解决加载闪烁时出现vue标签或指令符号
Object.defineProperty //双向绑定的原生实现方法
复制代码
3.常用模板语法与常用命令指令
v-cloak:防止闪烁解决显示vue标签
v-model:多用于表单元素实现双向数据绑定
v-for:列表渲染
v-show:显示内容
v-if:显示与隐藏 (dom元素的删除添加默认值为false)
v-else-if:必须和v-if连用
v-else:必须和v-if连用 不能单独使用 否则报错 模板编译错误
v-bind:动态绑定 作用: 及时对页面的数据进行更改,缩写:
v-html:解析html标签
复制代码
4.事件处理
v-on:keyup:键盘事件
v-on:keyup.enter:回车键
复制代码
5.computed计算属性
computed用来监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可以在页面上进行双向数据绑定展示出结果,可以做逻辑处理的变量。
举例:购物车里面的商品列表和总金额之间的关系,只要商品列表里面的商品数量发生变化,或减少或增多或删除商品,总金额都应该发生变化。这里的这个总金额使用computed属性来进行计算是最好的选择
复制代码
6. watch监听
watch主要用于监控vue实例的变化,它可以监控一个data里面的数据,computed,路由的变化。
特点:
1、监听获取两个值一个是新值,另一个是旧值
2、可以深度监听
3、可以利用watch监听路由的特性做转场动画
computed:{
getName(){
return this.name;
}
},
watch:{
//监听data里面的值
name(newVal,oldVal){
console.log("newVal:"+newVal,"oldVal:"+oldVal);
},
//监听computed里面的值
getName(newVal,oldVal){
console.log("computed-newVal:"+newVal,"computed-oldVal:"+oldVal);
},
复制代码
2. VUE 基础
1.全局Filter过滤
Vue.filter("increase",function(value,num1,num2){
return parseInt(value)+parseInt(num1)+parseInt(num2);
});
复制代码
2.局部Filter过滤
filters:{
formatDate:function(val){
if(val!==''){
val=val.split("-");
val=val[0]+"年"+val[1]+"月"+val[2]+"日"
}
return val;
}
},
template:`<div>日期:{{"2019-09-11"|formatDate}}</div>`
复制代码
3.父子组件传值
- 父组件传值子组件
<ChildComponent title="我是子组件"></ChildComponent>
//子组件接收方式
props:{
title:{
type:String //数据类型
required:true //是否必须传值,true:必须,false:可选
}
}
复制代码
- 子组件传值父组件
<button type="button" @click="sendParent()">给父组件传值</button>
//子组件方法
methods:{
sendParent(){
this.$emit("getChild","我是子组件传过来的值");
}
}
//父组件代码
<ChildComponent title=“我是子组件” @getChild="getParent($event)"></ChildComponent>
//方法
methods:{
getParent(data){
//接收父组件HomeComponent传过来的值
console.log(data);
}
}
复制代码
4.兄弟组件传值
- 使用 bus.$.on(‘getA’,(message)=>{})
////定义一个总线bus
let bus=new Vue;
//用$on接收
bus.$emit("getA","你好");//用$emit传值B
//B接收
bus.$on("getA",(message)=>{
console.log(message);
this.text=message;
})
复制代码
5.Slot插槽
可以获取组件里的内容。
应用场景:自定义组件使用,比如自定义button按钮。
复制代码
let ButtonComponent={
template:` <button type="button" class="btn"><slot></slot></button>`,
mounted:function(){
//获取插槽里的内容
if(this.$slots.default!=null){
console.log(this.$slots.default[0].elm.innerHTML);
}
},
};
复制代码
new Vue({el:"#app",
components:{'my-button':ButtonComponent},
template:`<div><my-button>提交</my-button></div>`
})
复制代码
6.自定义指令
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
<input type=“text” placeholder=“用户名” v-focus />
复制代码
- 注册一个局部指令
v-position
// 注册一个局部指令 `v-position`
directives:{position:{
bind:(el,binding)=>{
el.style.position="absolute";
el.style[binding.arg]=binding.value+"px";
}
}
}
<div v-position:left="'200'" class="box"></div>
复制代码
3.VUE 的生命周期执行顺序
beforeCreate:初始化之前
created:初始化完成(不能获取dom,一般用于获取ajax数据)
beforeMount:挂载之前
mounted:挂载完成之后(可以获取dom)
beforeUpdate:数据更新之前
updated:数据更新之后。应用场景:可以做数据更新后获取焦点,也可以获取dom的动态属性,更改数据时对dom进行操作。beforeDestroy:解除绑定之前(页面离开)
destroyed:解除绑定之后(页面离开)
activated:keep-alive组件激活时调用。该钩子在服务器端渲染期间不被调用。用于性能优化缓存dom和数据。deactivated:keep-alive组件停用时调用。该钩子在服务端渲染期间不被调用。
复制代码
4.VUE config的配置
1.vue.config.js配置
module.exports={
publicPath:'/',//配置根目录
outputDir:'dist',//构建输出目录
assetsDir:"assets",//静态资源目录(js,css,image)
lintOnSave:false, //是否开启eslint检测,false不开启,有效值:true || false
productionSourceMap: true,//生成环境下面开启sourceMap支持断点调试
devServer:{
open:true, //是否启动打开浏览器
host:"0.0.0.0",//主机,0.0.0.0支持局域网地址,可以用真机测试
port:8080, //端口
https:false,//是否启动https
//配置跨域代理http,https
proxy:{
"/api":{
target:"http://vueshop.glbuys.com/api",
changeOrigin:true,
pathRewrite:{
'^/api':""
}
}
}
},
configureWebpack:{
devtool: 'source-map' //配置开发者环境的sourceMap用于断点调试
}
};
复制代码
5.eslint的使用
/*eslint-disable*/ 禁用eslint检测
/*eslint-enable*/ 开启eslint检测
复制代码
6.移动端适配方式
1.移动端适配
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0,user-scalable=no" />
复制代码
width:设置layout viewport 的宽度,为一个正整数,或字符串"device-width"
initial-scale:设置页面的初始缩放值,为一个数字,可以带小数
minimum-scale:允许用户的最小缩放值, 为一个数字,可以带小数
maximum-scale:允许用户的最大缩放值,为一个数字,可以带小数
height:设置layout viewport 的高度,这个属性对我们并不重要,很少使用
user-scalable:是否允许用户进行缩放,值为"no"或"yes", no 代表不允许,yes代表允许
复制代码
2.format-detection使用
format-detection使用
<meta name=“format-detection” content=“telephone=no,email=no,date=no,address=no” />
telephone:电话
eamil:邮箱
date:日期
address:地址
复制代码
3.禁用IE兼容模式
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
复制代码
4.使用手淘flexible.js 计算rem
- 计算rem
比如:750px设计稿,那么1rem=75px, div的高是50px ,50px换算成rem公式:
50px/75px=0.7rem;
复制代码
- 解决1px 细线问题
在retina(视网膜)屏上面, devicePixelRatio(物理像素)这个值是2或3, 所以1px长度映射到物理像素上就有2px或3px那么长。
复制代码
//designWidth:设计稿的实际宽度值,需要根据实际设置
//maxWidth:制作稿的最大宽度值,需要根据实际设置
//这段js的最后面有两个参数记得要设置,一个为设计稿实际宽度,一个为制作稿最大宽度,例如设计稿为750,最大宽度为750,则为(750,750)
;(function(designWidth, maxWidth) {
var doc = document,
win = window,
docEl = doc.documentElement,
remStyle = document.createElement("style"),
tid;
//浏览器竖屏与横屏转换的BUG。
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
maxWidth = maxWidth || 540;
width>maxWidth && (width=maxWidth);
var rem = width * 100 / designWidth;
remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
}
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(remStyle);
} else {
var wrap = doc.createElement("div");
wrap.appendChild(remStyle);
doc.write(wrap.innerHTML);
wrap = null;
}
//要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次;
refreshRem();
win.addEventListener("resize", function() {
clearTimeout(tid); //防止执行两次
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener("pageshow", function(e) {
if (e.persisted) { // 浏览器后退的时候重新计算
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);
if (doc.readyState === "complete") {
doc.body.style.fontSize = "16px";
} else {
doc.addEventListener("DOMContentLoaded", function(e) {
doc.body.style.fontSize = "16px";
}, false);
}
})(750, 1024);
复制代码
7.自定义封装组件
- 注册组件
export default{
install(Vue){
Vue.component("my-button",Button);
}
}
//使用组件
import Vue from 'vue';
import Button from '../components/button’
Vue.use(Button)
复制代码
8.Vue路由
1.安装路由
//安装最新版本
npm install --save vue-router
//安装指定版本
npm install --save vue-router@3.0.3
复制代码
2.路由配置
- 建立router.js 文件
import Vue from 'vue';
import Router from 'vue-router';//引用路由
import HomePage from './pages/index';
Vue.use(Router);//装载路由
//路由实例化
let router=new Router({
mode:"hash", //1、hash哈希:有#号。2、history历史:没有#号
base: process.env.BASE_URL,//自动获取根目录路径
routes:[
{
path:"/",
name:"index",
component:HomePage
},
{
path:'/news',
name:"news",
//路由懒加载
component:()=>import("./pages/news")
},
]
});
export default router;
复制代码
- main.js 配置路由
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
复制代码
- APP.vue
<template>
<div>
<router-view/>
</div>
</template>
复制代码
3.动态路由
routes:[
{
path: '/news/:id',
name: 'news',
component: () => import('./views/News.vue'),
},
]
<router-link to=“/news/10">新闻页面</router-link>
复制代码
4.路由的跳转
- 跳转方式 1
<router-link to=“/about">About</router-link>
复制代码
- 跳转方式 2
//push进入跳转历史记录
this.$router.push({path:’/about’})
复制代码
- 跳转方式3
//replace不进入跳转历史记录
this.$router.replace({path:’/about’})
复制代码
5.路由的传参
- 传参方式1
<router-link to=“/about?id=10">About</router-link>
复制代码
- 传参方式2
//params:参数不显示url地址上
this.$router.push({name:’about’,params:{id:10}})
复制代码
- 传参方式3
//query:参数显示在地址上[推荐]
this.$router.push({path:’/about’,query:{id:10}})
复制代码
6.路由接收参数
- 接收参数方式1
this.$route.params.id
复制代码
- 接收参数2
this.$route.query.id
复制代码
- 返回上一级
this.$router.go(-1)
复制代码
7.路由嵌套
{
path: "/admin",
name: "admin",
component: () => import("../views/admin/index/index"),
redirect: "/admin/column",
meta: {auth: true},
children: [
{
path: 'bannerShow',
name: "首页展示",
component: () => import("../views/admin/bannerShow/bannerShow"),
meta: {auth: true, keepAlive: false}
},
{
path: 'column',
name: "栏目管理",
component: () => import("../views/admin/column/index"),
meta: {auth: true, keepAlive: false}
}
]
}
复制代码
8.路由钩子函数与路由认证
{
path:'/user/profile',
component: ()=>import('./user/profile.vue'),
meta: { title: '个人资料',auth:true }
}
//auth:true表示这个页面需要进行会员认证,auth就是一个标识
复制代码
9.路由守卫
- beforeEach- 全局路由守卫
const router = new VueRouter({ ... })
router.beforeEach(function (to, from, next) {
if(to.meta.auth){
if(Boolean(store.state.isLogin)==true){//已登录
next();
}else{//未登录
next({"/login/index"});
}
}else{
next()
}
});
复制代码
10.路由守卫独享
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
//….
}
}
]
})
复制代码
11.组件内的守卫
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this`
}
复制代码
12.路由histroy和hash模式的区别
hash模式:路由地址带#号。适合做后台管理系统
history模式:路由地址不带#号。适合做前端宣传页面。但是history模式有个问题就是刷新页面会出现404错误,解决方法需要配置服务器。
复制代码
nginx解决方案:
location / {
try_files $uri $uri/ /index.html;
}
复制代码
八、Vuex状态管理
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。将数据分发给各个组件,异步数据流,统一封装接口。
应用场景比如:购物车、会员登录等需要跨页面,跨组件实时传递数据的地方。
1.基础应用
1.安装Vuex
npm install --save vuex
复制代码
2.使用Vuex
//导入vuex
import Vuex from 'vuex'
//启用vuex
Vue.use(Vuex)
//实例化对象
let store=new Vuex.Store({
state:{}//初始化数据
mutations:{}//同步操作方法
actions:{}//异步操作,用于操作mutations里面的方法,如果mutations里面的方法操作量大最好写在actions里面。
getters:{}//有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数
})
复制代码
new Vue({
el: '#app',
router,
store,//挂载到vue里使用
components: { App },
template: '<App/>'
})
复制代码
3.state
state:定义vuex的数据源。
state:{
total:0,
users:[
{id:1,name:"张三",age:18},
{id:2,name:"李四",age:20},
{id:3,name:"王五",age:22},
{id:4,name:"赵六",age:25}
]
}
复制代码
- 页面调用方式 1
this.$store.state.count
复制代码
- 页面调用方式2
import { mapState } from 'vuex'
computed:{
...mapState({
total:"total"
})
}
methods:{
this.total;
}
复制代码
4.mutations
mutions :同步方式的方法提交,将改变的值赋给state数据源。
mutations:{
increment(state,payload){
state.total = payload.count;
}
}
//调用
this.$store.commit("increment",{count:10});
复制代码
- 辅助函数提交
import { mapMutations } from 'vuex’
methods: {
//方式一
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
]),
//方式二
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
复制代码
5. actions
actions :异步方式的方法提交,用于操作mutions里面的方法,实际应用里面获取ajax异步数据。
actions:{
inc(conText,payload){
conText.commit("increment",payload);
}
}
//页面使用
this.$store.dispatch(“increment”,{count:10});
复制代码
- 辅助函数提交
import { mapActions } from 'vuex’
methods: {
//方式一
... mapActions ([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
]),
//方式二
... mapActions ({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
复制代码
6.getters
gettters :可以认为是 store 的计算属性,类似于computed,例如对列表进行过滤并计数。
getters:{
getUsers(state){
let aUsers=state.users.filter((res)=>{
return res.age>18;
})
return aUsers;
}
}
//页面使用
this.$store.getters.getUsers
复制代码
- 辅助函数
import {mapGetters} from 'vuex’
computed: {
//方式一
...mapGetters(['getUsers']),
//方式二
...mapGetters({
getUsers:'getUsers'
})
}
复制代码