Vue.js的路由、vue-resource、es6语法、vuex

5、路由介绍

(1)基础介绍

  · vue-route用来构建SPA

  · html标签跳转(类似于a):<route-link to="路由"></route-link>或js中this.$route.push({path:''})

三种绑定

  1、to="/apple"

  2、:to="{path: '/apple'}"

  3、:to="{name: 'Apple'}"

在route-link中加tag="li"可以指定为li标签(默认为a标签)

· 渲染<route-view></route-view>

  · 安装

cnpm install vue-router --save           --save保存在package.json中

  · 使用

import Router from 'vue-router'
Vue.use(Router)

(2)动态路由

  · /user/:username       :username可以随意变化

测试:

在src/route/index.js下

import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'   // @代表别名是src的映射
import GoodsList from './../views/GoodsList'   // 引入的组件取名和路径,.vue后缀可以省略

Vue.use(Router)

export default new Router({
  routes: [
    {
    	path: '/goods/:goodsId',    // 路由
    	name: 'GoodsList',   // 路由名
        component: GoodsList   // 引入组件名
    }
  ]
})

在src/views/GoodsList.vue中

<template>
  <div>
    这是商品列表页
    <span>{{ $route.params.goodsId}}</span>     <!--获取路由的参数后面是参数名-->
  </div>
  
</template>

效果:



对于上面路由中的#号,是因为采用了hash模式的命名,可改为history模式,便不会有#号

export default new Router({
mode: 'history',
routes: [
    {
    	path: '/goods/:goodsId',
    	name: 'GoodsList',
        component: GoodsList
    }
  ]
})

(3)嵌套路由

在index.js里

{
    	path: '/goods',
    	name: 'GoodsList',
        component: GoodsList,
        children: [
        	{
        		path: 'title',   // 前不能加/否则就是根 == /goods/title
        		name: 'title',
        		component: Title
        	},
        	{
        		path: 'img',
        		name: 'img',
        		component: Image
        	}
        ]
    }

在GoodsLIst.vue里

<template>
  <div>
    这是商品列表页
    <span>{{ $route.params.goodsId}}</span>
    <router-link to="/goods/title">显示标题</router-link>
    <router-link to="/goods/img">显示图片</router-link>
    <div>
      <router-view></router-view>
    </div>
  </div>
  
</template>

(4)编程式路由,js中定义

在GoodsList.vue中

<template>
  <div>
    这是商品列表页
    <span>{{ $route.params.goodsId}}</span>
    <button @click="cart">购物车页面</button>
  </div>
  
</template>

定义点击方法:

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    cart() {
      this.$router.push("/cart");
    }
  }
  
}
</script>

传参时:this.$router.push({path: 'cart?goodsId=122'});

获取参数:$route.query.goodsId

注:使用/goodsList/:goodsId时,获取参数:$route.param.goodsId

(5)命名视图

<route-view name="viewA"></route-view>               不同的route-view显示不同的组件
<route-view name="viewB"></route-view>

routes: [
    {
        path: '/apple',
        component: {
            viewA: apple,
            viewB: applePagr
        }
    }
]

(6)重定向

route: [
    {
        path: '/',
        redirect: '/apple'                  首页重定向到apple页面
    }
]

6、vue-resource基础介绍

(1)使用安装

  · <script src="https://cdn.jsdelivr.net/vue.resource/1.3.1/vue-resource.min.js"></script>

lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/mall
$ cnpm install vue-resource
Recently updated (since 2018-02-16): 2 packages (detail see file E:\workspace\xampp\htdocs\demo\mall\node_modules\.recently_updates.txt)
import VueResource from 'vue-resource'

Vue.use(VueResource)

(2)7种api

get、head、delete、jsonp、post、put、patch

(3)使用

created: function() {
    this.$http.get('getList')         // 请求
    .then(function(data) {            // 请求成功  == .then((res) => {this.newList = res.data}, (err) => {})
      console.log(data)
    }, function(err) {                // 请求失败
      console.log(err)
    })
  },
this.$http.post('getList', {userId: 111})


this.$http.get()

7、es6语法

(1)使用import引入,使用export default导出

import Hello from './components/Hello'

export default {
    components: {
        Hello                                    相同时:== Hello: Hello
    }
}

(2)let和var的区别

let:当前作用域,外层取不到

var:在外也可以访问

const:常量

(3)函数缩写

data () {} == data: function() {}

8、vuex:状态管理插件,是一个公共的数据仓库,多个组件状态一致,如:登录百度时,百度贴吧状态一致

(1)安装

$ cnpm install vuex --save

(2)使用在main.js中

import Vuex from 'vuex'

Vue.use(Vuex)

(3)实例

main.js中

const store = new Vuex.Store({                   定义一个store
	state: {
		totalPrice: 0                    数据仓库
	},
	mutations: {                             自定义的动作
		increment (state, price) {       1、就是state,2、price后面调用这个动作时传递的参数
			state.totalPrice += price
		},
		decrement (state, price) {
			state.totalPrice -= price
		}
	}
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,                                        全局注册
  components: { App },
  template: '<App/>'
})
app.vue中
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <p>{{ totalPrice }}</p>
    <apple></apple>
    <banana></banana>
  </div>
</template>

<script>
import Apple from './components/Apple'
import Banana from './components/Banana'

export default {
  components: {Apple, Banana},
  computed: {
    totalPrice () {
      return this.$store.state.totalPrice      通过$store.state.totalPrice获取数据

    }
  }
}
</script>

apple.vue

<template>
  <div id="app">
    <p>i am apple</p>
    <button @click="addOne">add one</button>
    <button @click="minuxOne">minus one</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      price: 5
    }
  },
  methods: {
    addOne () {
      this.$store.commit('increment', this.price)        通过$store.commit传递给mutations中的动作,(动作名,参数)
    },
    minuxOne () {
      this.$store.commit('decrement', this.price)
    }
  }
}
</script>

(4)actions的使用

const store = new Vuex.Store({
	state: {
		totalPrice: 0
	},
	mutations: {
		increment (state, price) {
			state.totalPrice += price
		},
		decrement (state, price) {
			state.totalPrice -= price
		}
	},
	actions: {
		increase (context, price) {
			context.commit('increment', price)           通过调用mutations中的动作,间接改变值
		}
	}
})
methods: {
    addOne () {
      this.$store.dispatch('increase', this.price)                   使用dispatch绑定
    },
    minuxOne () {
      this.$store.commit('decrement', this.price)
    }
  }

(5)使用getters取数据

state: {
		totalPrice: 0
	},
	getters: {
		getTotal (state) {
			return state.totalPrice
		}
	},
computed: {
    totalPrice () {
      return this.$store.getters.getTotal          通过getters取出数据
    }
  }





猜你喜欢

转载自blog.csdn.net/snow_small/article/details/79370038