npm命令
- 卸载:npm uninstall 包名 -g
- 查看本地已安装的包:npm ls 包名 -g
- 查看本地已安装的所有包:npm list -g
- 搜索包的所有版本:npm view 包名 versions
安装
安装脚手架 VueCli:
- 卸载旧版本:
npm uninstall vue-cli -g
, - 安装:
npm install -g @vue/cli
- 查看安装的VueCli版本:
vue --version
创建Vue项目:vue create 项目名
(项目名不能驼峰、不能中文)
基础
v-text
、v-html
指令会干掉标签里的内容
v-if
:元素销毁和重建实现是否显示
v-for
:遍历数组<div v-for='(item,index) in arr' :key='index'>{{item}}</div>
v-for
:遍历对象<div v-for='(item,key,index) in obj' :key='index'> {{item}}</div>
v-once
:只渲染元素和组件一次,重新渲染时被视为静态内容跳过 <div v-once>一定不修改:{{ msg }}</div>
侦听器
```html
```
过滤器
用于对文本进行格式化 过滤器可以用在两个地方:{{}} 和 v-bind表达式
```html
<p>过滤后的电话:{{phone | pp}}</p> // 不传参,有一个默认值接收值
<p>过滤后的电话:{{phone | qq(msg)}}</p>
```
事件
事件函数不加括号,默认第一个参数是事件对象$event
,加括号则需要手动传递事件对象$event
html <button @click="youcan(1,2,$event)">点我</button>
数据更新检测
数组更新
调用以下方法更新了原数组,页面会自动刷新同步:
javascript push()、pop()、shift()、unshift()、splice()、sort()、reverse()
调用以下方法修改数组后返回的是新数组,原数组不会改变,视图不会刷新,想要刷新,给原数组重新赋值
java filter() 、contact() 、slice()
对象更新
修改原对象property会触发视图更新,给原来对象添加property或删除property不会触发视图更新
Vue解决办法:
javascript this.$set(this.obj,'love','游泳') // 添加love属性 this.$delete(this.obj,'love') // 删除love属性
组件
数据传递
父传子
props:只能是父组件向子组件传递数据
```html
{{item}}
```
子传父
通过自定义事件传递数据,语法:
```javascript 子组件自定义事件
this.$emit('getMsg',msg,bill)
父组件接收事件并处理 <子组件 @getMsg='DealWith'>
methods:{
DealWith(msg,bill){
this.msg=msg;
this.bill=bill;
}
}
```
例子:
```html
```
父传子孙后代
```html
```
```html
```
异步组件
- 说明:使用组件的时候再去加载这个组件,提高代码执行速度
- 异步组件写法:--局部
- const CompB = ()=>import('./CompB.vue')
- 或者 components: { CompB:()=>import('./CompB.vue'), CompC:()=>import('./CompA.vue'), }
动态组件
通过组件的销毁和重建实现组件的动态切换,语法:
<component :is='加载的组件名称'></component>
```markdown :使组件不会被销毁,语法:
生命周期函数:activated、deactivated 只有被 包裹时才起作用: activated 切换到该组件时调用
deactivated 离开该组件时调用 ```
插槽
```html
<h4>默认内容</h4>
<slot name="footer"></slot>
生命周期
同级属性
```html
```
数据传递
父传子:Prop
子传父:自定义事件,this.$emit('自定义事件名', ' ')
访问根实例new Vue,this.$root.xx
操作DOM或子组件,给标签或组件加ref标记
```html
获取DOM
获取子组件 this.$refs.pp获取子组件 ```
父组件向子孙后代传递数据
provide / inject
,但绑定不是响应式的
Axios
get请求
js axios.get("/findAll?name=xiaochen").then(function(response){ console.log(response.data); }).catch(function(err){ console.log(err); });
post请求
javascript axios.post("/user/save",{ username:"xiaochen", phone:13260426185 }).then(function(response){ console.log(response.data); }).catch(function(err){ console.log(err); });
并发请求:同时发送多个请求,等响应结果都返回后再统一处理
```js function getUserAccount() { return axios.get('/user/12345'); }
function getUserPermissions() { return axios.get('/user/permissions'); }
axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 })); ```
拦截器
```js // 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 config.header["Token"] = "xxxx" return config;
}, function (error) { return Promise.reject(error); });
// 添加响应拦截器 axios.interceptors.response.use(function (response) {
if (response.status === 200){ return response.data } else { return Promise.reject(new Error('error')) } }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); ```
路由
安装:npm i vue-router -S
this.$route:当前组件对应的路由
this.$router:全局路由对象
动态路由
js const router = new VueRouter({ routes: [ // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } ] })
嵌套路由
js const router = new VueRouter({ routes: [ { path:'/zhinan', component:Zhinan, children:[//二级路由 { path:'anzhuang', component:, { path:'base', component:, } ] }, { path:'/**' component:NotFound } ] })
路由跳转
跳转路由 - 编程式跳转 this.$router.push({ name: 'User', params: { uname: 123,id:xx } })
router-link 的 to 属性传一个对象
html <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> <router-link to="/zhinan">User</router-link>
路由传参
语法:
js const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, props: true }, ] })
组件内获取参数: props:['id']
路由守卫
VueX
state:存储数据
mutations:修改数据,不能执行异步操作
action:操作mutations,可以任意执行异步操作
getters:操作state中的数据,并在getters方法中单独缓存,响应式,类似计算属性computed
modules:把store中的数据和方法分成模块
store中:
```html
```
state
读取state中数据,{{this.$store.state.msg}}
mutations
用于修改state中数据
```html
```
actions
```html
```
modules
组件中
```html
城市模块使用
state
当前城市-state:{{ $store.state.cityModule.cityName }}
辅助函数mapState:{{ cityName }}
<h4>getters</h4>
<p>getters-获取数据:cityVal:{{ $store.getters['cityModule/cityVal'] }}</p>
<p>getters-辅助函数:{{ cityVal }}</p>
<h4>mutations</h4>
<button @click="getCity1"> 修改城市成名</button>
<button @click="getCity2"> 辅助函数-修改城市成名</button>
<h4>actions</h4>
<button @click="updateCity"> actions-修改城市成名</button>
<button @click="updateCity2"> actions-辅助函数-修改城市成名</button>
```
store.js中
```js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
const store = new Vuex.Store({ //5. 模块 用户信息 城市数据 购车数据 搜索数据 ... modules:{ //5.1 城市数据 cityModule:{ namespaced:true,//开启命名空间 让actions mutations getters的作用域是当前的模块下 state:{ cityName:'北京' }, getters:{ cityVal:state=>{ return state.cityName +'帝都' } }, mutations:{ changeCity(state,payload){ state.cityName = payload } }, actions:{ getCity(context,city){ context.commit('changeCity',city) } } } } }) //导出 export default store; ```
局部模块访问全局模块,只有getters和actions有此功能
```js export default { namespaced:true, state:{ cityName:'北京' }, mutations:{ changeCity(state,payload){ state.cityName = payload } }, getters:{ // state和getters访问本模块内的,rootState和rootGetters访问全局的 getGlobalCity(state,getters,rootState,rootGetters){ console.log('-cityModule-getters',state,getters,rootState,rootGetters); } }, actions:{ //局部context对象可以访问全局state getters mutations actions和其他模块 //context={dispatch:'',commit:'',state:'',getters:'',rootState:'',rootGetters} getGlobalAction(context){ console.log(context);
//可以访问全局到的actions和mutations,加入第三个参数
context.commit('changeUser','全局的user',{root:true});
}
}
} ```