Vue+element+Nodejs学习记录(5)

26 篇文章 0 订阅
23 篇文章 1 订阅

1.Vue基础使用

vue-cli 3.x创建项目

npm install -g @vue/cli
vue create hello-world 或者 vue ui

cd 目录
vue run serve

参考文章:https://www.cnblogs.com/niwalala/p/9253746.html

Vue中使用element

1.在项目根目录执行命令:npm i element-ui -S进行安装

2.在main.js中引入element:
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Element)

3.然后在.vue文件里就直接可以用了

参考文章:
https://blog.csdn.net/qq_37164847/article/details/80939741
https://www.cnblogs.com/yuyujuan/p/10267749.html

Vue中的跨域请求

因为端口号不同,比如后端api接口可能是8000,Vue的端口是是8080,会涉及到跨域,所以我们要在vue.config.js中设置应该服务器代理。代码如下:

proxyTable: {
  '/api': {                 //使用/api代理对3000端口服务的请求
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': '/api'
    }
  },
},

也可以在服务端设置CORS进行跨域。

router-link和router-view

<template>
	
  <div id="app">

    <div id="nav">
     <!-- 使用 router-link 组件来导航. -->
     <!-- 通过传入 `to` 属性指定链接. -->
     <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
      <router-link to="/"></router-link>
    </div>

    <keep-alive>
		<!-- 路由出口 -->
  		<!-- 路由匹配到的组件将渲染在这里 --> 		   
    	<router-view/>
    </keep-alive>

  </div>

</template>

<style scoped>

</style>

// '/'路由对应Home组件,所以Home组件内容将会渲染到router-view部分
export default new Router({
  routes: [
    {
		path: '/',
		name: 'Home',
		component: Home,
    },
    {
		path:'/city',
		name:'City',
		component: City
    },
    {
    	//动态路由,前面是/detail后面带一个参数,放入id变量中
    	path:'/detail/:id',
    	name:'Detail',
    	component:Detail

    }
  ],
  scrollBehavior(to,from,savedPosition){
    return {x:0,y:0}
  }
});

2.Vue router、Axios、Vuex使用

我们需要弄懂这几个常用的概念。

Vue router

使用 Vue.js 做项目的时候,一个页面是由多个组件构成的,所以在跳转页面的时候,并不适合用传统的 href,于是 vue-router 应运而生。

对于router-link和router-view上面解释了,使用Vue router创建好router.js文件后,就可以使用router-link和router-view进行页面跳转了。

//router.js
import Home from './components/home.vue'

const routers = [
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/',
    component: Home
  },
]
export default routers

这种只需要跳转页面,不需要添加验证方法的情况,可以使用router-link来实现导航

在这里插入图片描述

在编译之后,<router-link>会被渲染为<a>标签, to 会被渲染为 href,当<router-link>被点击的时候,url 会发生相应的改变。

实际情况下,有很多按钮在执行跳转之前,还会执行一系列方法,这时候可以使用this.$router.push(location)来修改url,完成跳转

在这里插入图片描述
在这里插入图片描述

axios

Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource,目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求。

//axios get请求
axios.get("/user?ID=12345")
    .then(function(res){//成功执行的函数
    	console.log(res)
	})
    .catch(function(err){//失败执行的函数
    	console.log(err);
	})

//axios  post请求
axios.post("/user",{
    firstName:'志武',
    lastName:"胡"
})
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})

Vuex

Vuex 应用的状态 state 都应当存放在 store.js 里面,Vue 组件可以从 store.js 里面获取状态,可以把 store 通俗的理解为一个全局变量的仓库。

但是和单纯的全局变量又有一些区别,主要体现在当 store 中的状态发生改变时,相应的 vue 组件也会得到高效更新。

在 src 目录下创建一个 vuex 目录,将 store.js 放到 vuex 目录下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 定义状态
  state: {
    author: 'Wise Wrong'
  }
})

export default store

将状态映射到组件

<template>
  <footer class="footer">
    <ul>
      <li v-for="lis in ul">{{lis.li}}</li>
    </ul>
    <p>
      Copyright&nbsp;&copy;&nbsp;{{author}} - 2016 All rights reserved
    </p>
  </footer>
</template>

<script>
  export default {
    name: 'footerDiv',
    data () {
      return {
        ul: [
          { li: '琉璃之金' },
          { li: '朦胧之森' },
          { li: '缥缈之滔' },
          { li: '逍遥之火' },
          { li: '璀璨之沙' }
        ]
      }
    },
    computed: {
      author () {
        return this.$store.state.author
      }
    }
  }
</script>

这是 footer.vue 的 html 和 script 部分,主要在 computed 中,将 this.$store.state.author 的值返回给 html 中的 author,页面渲染之后,就能获取到 author 的值。

在组件中修改状态

然后在 header.vue 中添加一个输入框,将输入框的值传给 store.js 中的 author

这里我使用了 Element-UI 作为样式框架

在这里插入图片描述

上面将输入框 input 的值绑定为 inputTxt,然后在后面的按钮 button 上绑定 click 事件,触发 setAuthor 方法

methods: {
 setAuthor: function () {
   this.$store.state.author = this.inpuTxt
 }
}

在 setAuthor 方法中,将输入框的值 inputTxt 赋给 Vuex 中的状态 author,从而实现子组件之间的数据传递。

官方推荐的修改状态的方式

上面的示例是在 setAuthor 直接使用赋值的方式修改状态 author,但是 vue 官方推荐使用下面的方法:

在这里插入图片描述

首先在 store.js 中定义一个方法 newAuthor,其中第一个参数 state 就是 $store.state,第二个参数 msg 需要另外传入

然后修改 header.vue 中的 setAuthor 方法

在这里插入图片描述

这里使用 $store.commit 提交 newAuthor,并将 this.inputTxt 传给 msg,从而修改 author

这样显式地提交(commit) mutations,可以让我们更好的跟踪每一个状态的变化,所以在大型项目中,更推荐使用第二种方法。

Vuex状态管理流程:view——action——mutations——state——views

1.mutations直接改变state的数据

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
})


//调用
this.$store.commit('change')//这里传入的是你要调用的函数的名字

2.actions通过mutation来改变状态,而不是直接改变状态

actions内部可以有异步操作,而mutations不行

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    }
)

//如何调用
this.$store.dispatch('actionChange')

3.getters 获取状态的同时,进行判断

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    },
    getters:{
        getName(state){
            return state.name===''?'胡志武':state.name
        }        
    
//调用
this.$store.getters.getName
)

4.Vuex的模块里的状态

new Vuex.Store({
    modules:{
        user:{
            state:{
                admin:'胡志武'
            },
            mutations:{},
            ...
        }
    }
})
// 如何访问
    this.$store.state.user.admin

参考文章:
https://www.cnblogs.com/wisewrong/category/933810.html
https://juejin.im/post/5ce810786fb9a07ea9444af1
https://juejin.im/entry/597ab13d5188253e0a62efcb
https://segmentfault.com/a/1190000012116116#articleHeader12
https://www.cnblogs.com/keepfool/p/5690366.html
https://juejin.im/post/5a0ea4ec6fb9a0450407725c

官方参考资料:
axios:https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B
Vue-router:https://router.vuejs.org/zh/guide/#html
Vuex:https://vuex.vuejs.org/zh/

3.axios请求拦截和响应拦截

import axios from 'axios'
import { Message, Loading } from 'element-ui';
import router from './router'

//http.js对axios进行封装

let loading        //定义loading变量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

// 请求拦截  设置统一header
axios.interceptors.request.use(config => {
    // 加载
    startLoading()
    if (localStorage.eleToken)
        config.headers.Authorization = localStorage.eleToken
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截  401 token过期处理
axios.interceptors.response.use(response => {
    endLoading()
    return response
}, error => {
    // 错误提醒
    endLoading()
    Message.error(error.response.data)

    const { status } = error.response
    if (status == 401) {
        Message.error('token值无效,请重新登录')
        // 清除token
        localStorage.removeItem('eleToken')

        // 页面跳转
        router.push('/login')
    }

    return Promise.reject(error)
})

export default axios
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值