Vue入门学习(1)----Vuex
vue语法学习和使用;个人觉得首要的是先理解概念问题,代码都是相通的文章目录
- Vue入门学习(1)----Vuex
- 前言
- 一、vue是什么?
- 二、入门语法
- WebPack:前端模块化打包工具
- 三、 VueX
- 四、Vue-Cli
- 五、vue router 路由
- 总结
前言
提示:这里可以添加本文要记录的大概内容:
随着前端的崛起,越来越多的人使用vue的学习,本文就介绍了Vue的语法和使用例子
提示:以下是本篇文章正文内容,下面案例可供参考
一、vue是什么?
二、入门语法
1.将值插入到模板内容:v-text 、v-html、v-pre、:
v-text:操作文本;直接输出所有文本信息。 v-html:操作标签;会解析标签 v-pre:用于显示原本的mustache语法url:<a href ='baidu.com'>百度一下<a>
<p v-html="url"></p>
<p v-text="url"></p>
<p v-pre>{{url}}</p>
<p v-cloak></p>
显示结果
百度一下
<a href ='baidu.com'>百度一下<a>
{{url}}
v-cloak:基本不用
v-cloak:在vue解析之前,div中有一个属性v-cloak ,vue解析之后,div中没有一个属性v-cloak
cloak斗篷:解决解析js的时候卡住了
场景:预加载填充
代码解释:在js代码还没有加载出来的时候,隐藏{{message}} 。加载出来了,就显示{{message}}
<style>
[v-cloak]{
display:none;
}
</style>
<div v-cloak>{{message}}</div>
2.v-on =>@click
代码如下(示例):
v-bind:将数据动态绑定到属性、class里
v-bind:src
<!--语法糖的写法: -->
<img :src="url"/>
<a :href="url"/>
<div :class="activa"></div>
3.v-show和v-if
代码如下(示例):
v-show:操作样式;
v-if:操作dom;消耗大
4.completed:计算属性
代码如下(示例):
与方法的区别是使用多次,但是只调用一次;
completed:{
add:function(){
return this.a+this.b;
}
}
5.axios:类似于ajax,是对ajax的封装
安装代码如下:
npm install axios
6.Component:组件
6.1创建组件
const cpnC = Vue.extend({template:`<div></div>`});
6.2注册组件
Vue.Component(“my-cpn”,cpnC);
6.3使用组件
6.4 一般使用
Vue.Component(“my-cpn”,{ Vue.extend({template:`<div></div>`})});
为什么data在组件中必须是函数
页面跳转 replace和push区别
//replace 替换这个页面,无法回退
this.$routerrouter.replace('/home');
this.$routerrouter.push('/home');
7 Mustache 语法:{{}}
7.1不希望界面随意改变
<p v-once>{{message}}</p>
8. 父子组件之间传递参数 props emit
一般情况下,都是父组件向服务器发送请求
8.1子组件要使用父组件的参数:props
场景描述:加载列表的时候,父组件查出所有的结果,然后渲染到子组件
通过props向子组件传递数据
父组件:data(){message:“aaa”}
子组件:props:{cmessage}
父组件调用子组件:
子组件模板使用 {{cmessage}}
https://blog.csdn.net/jingtian678/article/details/81160995
8.2 父组件使用子组件的参数:emit
场景描述:点击子组件,父组件需要获取子组件的信息,向服务器发送请求
子组件发射事件—>父组件接受事件—>父组件接受使用事件
this.$emit(“btnClick”,item);
v-on:btnClick=“cpnClick”
methods:{cpnClick(item){ //事件实现}}
8.3 父组件访问子组件 $children 或者 $refs refs==reference(引用)
注: $children 一般不使用
//
this.$children[0].name;//通过下标去获取
//组件里
<cpn ref="a" ></cpn>
this.$refs.a; //$refs是一个对象类型,初始化为null
8.4 子组件访问父组件 $parent 或者 $root ;
一般不使用了
$root:直接访问Vue实例
9.data:在组件中存储变量,data必须是一个函数
即:
data(){
return{
}
}
10 slot:插槽
组件类似;
//组件里 定义一个具名插槽 就是有名字的插槽
<template id="cpn">
<p>返回</>
<slot name="center"><button>查询</button></slot> //默认使用按钮
</template>
//使用组件
<cpn> <span slot="center">查询</span><cpn>
10.2 slot 传值:
需求:通过插槽实现下面的效果
怎么通过父组件拿到子组件的数据
//:data是随意定义的 名字;可以:abc
11、编译作用域
父组件模板里的所有东西都会在父级作用域里面编译;
子组件模板里的所有东西都会在子级作用域里面编译;
//isShow是在父组件里面定义的。才会起作用
<cpn> <button v-show="isShow">查询</button><cpn>
12 导入导出
12.1 export :导出了模块,对外提供的接口
12.2 import 导入;加载对应的模块
打包工具
grunt gulp rollup webpack
其他
//可以将数组planguages通过-拼接。并去掉最后一个'-'
this.planguages.join("-")
WebPack:前端模块化打包工具
1、介绍
WebPack支持模块化开发。做底层的支持,让浏览器能够识别
1.1 主要和gulp对比
2、安装
依赖node.js环境。node.js为了能正常执行很多代码,必须依赖很多的包。所以安装node的时候,需要安装npm工具(npm是管理包的工具)
cnpm:是中国的
2.1 安装node.js 版本>8.9
2.2 安装webpack
指定版本号3.6.0。因为vue cli2依赖该版本
//-g 全局安装
npm install webpack@3.6.0 -g
//本地安装 在开发项目中 要在本地项目中安装 而不是全局安装;开发时依赖
npm install webpack@3.6.0 --save-dev
//查看版本
webpack -v
or
webpack --version
org:域名结尾的是非盈利组织
三、 VueX
1VueX概念
通俗解释:状态管理模式、集中存储管理,理解成:当有多个组件,希望多个组件的状态(变量)进行共享,vuex进行统一的管理,
简单理解:把需要多个组件共享的变量全部存储在一个对象里面,响应式:当该变量变了 其他的组件里的变量都跟着改变;
在多个界面需要共享的状态才放到vuex;
我把它理解全局session redis、session、cookies
常用在:用户登陆状态、用户名称、头像、地理位置信息
商品的收藏、购物车的商品
2 安装vuex
npm install vuex --save
3 VueX 使用
安装浏览器插件 devtools
浏览器=》更多工具=》扩展程序=》 Chrome 网上应用店
或者
https://www.jianshu.com/p/63f09651724c
https://blog.csdn.net/agua001/article/details/107357346
3.1 Vuex引入;src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
//1、安装插件
Vue.use(Vuex)
//2、创建对象
const store=new Vuex.Store({
state:{ //共享状态//设置属性 用来存储数据
counter:1000
},
mutations:{//devtools // //更改属性的状态
increment(state){
state.counter++;
},
decrement(state){
state.counter--;
}
},
actions:{
//应用 mutation
},
getters:{ //对应方法 用来获取属性的状态
},
modules:{
}
})
//3、导出
export default store
//4、挂载到vue 在mian.js
3.2 main.js 挂载到vue
import store from './store';
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3.3在view页面使用
<template>
<div>
<p>{{$store.state.counter}} </p>
<el-button type="primary" size="default" @click="add">+</el-button>
<el-button type="primary" size="default" @click="sub">-</el-button>
<hello-vuex></hello-vuex>
</div>
</template>
<script>
import HelloVuex from '../components/HelloVuex.vue'
export default {
name:"Test1",
components:{
HelloVuex
},
data(){
return{
message:"aaa"
}
},
methods:{
add(){
this.$store.commit("increment")
},
sub(){
this.$store.commit("decrement")
}
}
}
</script>
<style scoped>
</style>
HelloVuex.vue
<<template>
<p>{{$store.state.counter}} </p>
</template>
效果图:
注:相比直接调用$store.state.counter++,通过mutations之后,可以进行跟踪。
4 State:单一状态树;单一数据源;只有一个store
类比:很多信息需要被记录 :社保记录、公积金记录、户口等
信息被分散在很多的地方,要办理一个业务,比如:落户到成都,你需要去很多地方打印信息,到最后一个地方提交证明
非常低效、维护工作量很庞大
5 Getters: 计算state;数据需要变化后给view
第一种写法:每次计算平方的时候都要写这么长一串
第二种:在getters计算好了,页面直接调用就可以了
场景:计算counter的平方
<p>{{$store.state.counter * $store.state.counter}}</p>
<p>{{$store.getters.powerCounter}}</p>
store/index.js
getters:{
powerCounter(state){
return state.counter*state.counter
}
},
5.1
getters: {
powerCounter(state) {
return state.counter * state.counter
},
more20stu(state) {
return state.students.filter(s => s.age > 20)
},
//第二个参数只会是getters
more20stuLength(state, getters) {
return getters.more20stu.length;
},
//getters传递参数,比如:传年龄过来
moreAgeStu(state) {
// return function (age) {
// return state.students.filter(s => s.age > age)
// }
return age=>{
state.students.filter(s => s.age > age)
}
}
},
页面调用
<p>{{ $store.getters.powerCounter }} *</p>
<p>{{ $store.getters.more20stu }} *</p>
<p>{{ $store.getters.more20stuLength }} *</p>
<p>{{ $store.getters.moreAgeStu(20) }} *</p>
需求:多个地方展示年龄大于20的学生
6. Mutation:Vuex的store状态更新唯一的方式:提交Mutation
包含两部分:
1、字符串的事件类型;
2、一个回调函数。该函数的第一个参数是state
定义方式:
const store = new Vuex.Store({
state: { //共享状态
counter: 1000,
students: [{
name: "a",
age: 23
}, {
name: "a",
age: 10
}, {
name: "a",
age: 20
}, {
name: "a",
age: 25
}]
},
mutations: { //devtools
//increment类型;(state) {state.counter++;},回调函数
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
addcrementCount(state,payload){
//state.counter+=payload;
//特殊方式
state.counter+=payload.counter
},
addStu(state,stu){
state.students.push(stu);
}
},
通过mutation更新:
methods: {
add() {
this.$store.commit("increment");
},
sub() {
this.$store.commit("decrement");
},
addCount(count){
//1、普通提交封装
// this.$store.commit("addcrementCount",count);
//2、特殊的提交封装
this.$store.commit({
type:"addcrementCount",
count
})
},
addStudent(){
const stu={name:"asx",age:33}
this.$store.commit("addStu",stu);
}
}
注:参数被称之mutation的负载(payload)
<el-button type="primary" size="default" @click="addCount(5)">+5</el-button>
<el-button type="primary" size="default" @click="addStudent">添加学生</el-button>
Mutation响应式规则
Vuex的store中的state是响应式的,当state发生改变的时候,Vue组件会自动更新;
规则:
1、提前在store中初始化好所需的属性;
2、当给state中的对象添加新的属性时,使用下列方式:
(1) Vue.set(obj,‘newProp’,123)
(2) 用新对象给
四、Vue-Cli
Command Lines Interface:命令行界面;
快速搭建Vue开发环境和webpack配置;
使用前提:依赖 node.js
什么是NPM?
node package manage:是nodejs包管理和分发工具
-g -save 和-save-dev
-g 是全局安装; g:global
-dev 是保存到开发环境
Vue-Cli 使用
1、安装Vue-Cli
npm install -g @vue/cli
or
npm install @vue/cli -g
2、初始化项目Vue-Cli ;通过脚手架3创建方式:
// vue cli3初始化项目
vue create myvue
安装了脚手架3.没有安装2.需要拉取2的模板
npm install @vue/cli-init -g
//vue cli2初始化项目
vue init webpack myvue
vue-cli 3
vue-cli 3 基于webpack 4打造,设计原则:‘0配置’,移除了build和config等目录。提供 vue ui ,可视化配置。移除了static文件夹,新增了public文件夹,并将index页面移到了public
vue-cli 2 基于webpack 3打造
扩展
ESLint :对ES(js)的限制
箭头函数 =>
//1、
const aaa = function(){
}
//2
const obj={
bbb(){
}
}
//3、es6中定义函数
//const ccc =(参数列表)=>{
//}
const ccc =()=>{
}
//两个参数
const sum=(num1,num2)=>{
return num1+num2
}
//一个参数
const power=num1=>{
return num1 * num1
}
函数简写。语法糖
//函数中有多行代码
const test =()=>{
console.log("HHHH")
console.log("SSSS")
}
//函数中有一行代码,带有返回值,自动返回
const test =(num1,num2)=>num1+num2
const test =()=>console.log("SSSS") //返回的是undifine
五、vue router 路由
不会请求后台 刷新页面,只需要改hash; location.hash=‘home’;
或者在html5中可以 history.pushStated([],’’,‘home’)
HTML5中的 history模式
history.pushStated([],'','home');
history.back();//之前栈点移除
history.replaceState(([],'','home');//没有返回 后退
history.go(1) ==>history.forward()
history.go(-1) ==>history.back();
vue-router 安装
//安装路由
npm install vue-router --save
//导入路由
import Router from 'vue-router'
Vue.use(Router)
const routers =[{
{path:'',//路由默认路径。也可以'/'
//重定向
redirect:'/login'
}
{ path: '/login',
name: '登陆',
component: Login,
hidden:true},
{path: '/home',
name: '首页',
component: Home,}
]
const router =new Router({routers },mode:'history')//mode:'history' 去掉路径上的#号
//导出:目的是main.js中进行导入,挂载到vue
export default router
});
挂载到vue
import router from './router'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
使用路由
<router-link to='/login'></router>
<router-link to='/home'></router>
router-link
.router-link-active{
color:red;
}
选中的标签会变成红色
全局修改:
const router =new Router({routers },mode:'history',linkActiveClass:'active')
.active{
color:red;
}
通过代码的形式修改路由
this.$router.push('/home')
this.$router.replace('/home') //不能后退
动态路由 this.$route.params.abc
$route:处于活跃的路由
abc是在路由里面定义了的
/user/:abc
home页面:
data(){
return {userId:“zhangsan”}
}
//user页面获取 {{}userId}
computed:{
userId(){ return this.$route.params.abc}
}
路由的懒加载
项目打包 npm run build
官方:当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
作用:
将路由对应的组件打包成一个个的js代码块
只有路由访问的时候才会被加载
右边是路由懒加载的效果:
路由嵌套
{
path:'/home',
component:Home,
children:[{},{}]
}
全局导航守卫
概念:全局守卫
路由独享的守卫,
组件内的守卫:
场景:切换按钮的 时候 网页的title要通过按钮点击 跟着改变。
方式一:不好
export default{
created(){
document.title='首页'
}
}
方式二:监听路由。全局导航守卫
路由页面
const routes=[
{path:'/home',component:Home,
meta:{title:"首页"}
}
]
路由页面
//前置钩子(guard:守卫)。钩子hook:回调;
//路由跳转之前
router.beforeEach(function(to,from,next)){
//从from跳转到to
document.title=to.matched[0].meta.title
next() //必须,执行下一步
}
代码补充:后置钩子;不需要主动掉 next()
router.afterEach(function(to,from,next)){
//从from跳转到to
document.title=to.matched[0].meta.title
next() //必须,执行下一步
}
meta:元数据(描述数据的数据)
keep-alive 组件内部状态保留下来
keep-alive 是vue内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染;
router-view 也是一个组件,如果直接包在keep-alive里面,所有的路径匹配到的试图组件都会被缓存;
场景:我点了菜单,我希望再次点那个菜单的时候,之前点开的东西打开,而不是重新加载
<keep-alive>
<router-view />
</keep-alive>
keep-alive 可以实现 activated()/deactivated()
首页中使用path属性记录离开时的路径,在beforRouteLeave中记录
keep-alive 属性:
1、include:
2、exclude :将某个组件排除在外,不保留组件状态;不能随便加空格
<keep-alive exclude="User,Home">
<router-view />
<keep-alive>
案例:TabBar实现思路
在style中引用样式 @import ‘./assets/css/base.css’
扩展
reduce:移除
push:追加
VS Code 插件安装
频繁切换路由
用keepActive:
总结
本文仅仅简单介绍了vue的使用。ES6语法中。不需要分号