初步使用VUE

基于个人的理解

关于Vue

Vue是一个前端框架,最基本的用途就是添加在HTML元素中特定的指令,把DOM元素的属性和js中的数据绑定,这样省略了很多js与界面显示的数据交互代码。
例如:

<li class="items-nav-button" :class="{ 'item-nav-active' : hasPrevPage }" @click="toPrev">

就关联了vue中的数据hasPrevPage和方法toPrev

Vue会检测数据的变动,并且周期性的把变动反映在页面上。

最简单的使用,就是在每个页面定义一个Vue实例var vm = new Vue({....});,然而稍微大型的应用一般都是整体定义一个实例,各个页面通过子模块、路由、store等关联起来,构成一个应用。

关于Vue中的模块

定义一个js模块(文件),文件中导出的内容,也是一个Vue中的配置属性,不同的是,导出属性中,有一个template属性定义一个HTML模板,这样一个模块,可以被Vue复用。

Vue中可以全局以用,或者在一个页面/子模块中引用其他模块,引用后该模块可以作为标签,直接嵌入在html中。

例如一个模块

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

在引入后,可以被嵌入在其他模块中

import HelloWord from 'HelloWorld.js'
Vue.component("hello-world", HelloWord);

<div>
  <hello-world msg="WB" />
</div>

关于route

vue-router是vue的一个扩展组件,用于在多个模块间进行路由。

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'item',
    component: () => import('@/views/item/index'),
  },
  {
    path: '/shoppingCart',
    name: 'shoppingCart',
    component: () => import('@/views/shoppingCart/index')
  },
  {
    path: '/pickup',
    name: 'pickup',
    component: () => import("@/views/pickup/index")
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

$route会被注入到每个Vue实例中,可以通过他提供的各种方法进行页面跳转,如返回首页:

this.$router.replace("/");

Vuex

Vue的一个扩展组件

store

多页面跳转,传值是普遍需求,store组件用来统筹规划数据,按模块配置不同数据,提供了4类数据操作对象:

  • state: 类似Vue中的data,但是用于store内部访问,外部不进行直接操作
  • getters: 对外提供的获取state对象的方法
  • mutations: 提供操作state的方法
  • actions:类似mutations,但是支持异步

例如定义一个store:

export default new Vuex.Store({
  state: {
    stockId: localStorage.getItem("stockId") ? localStorage.getItem("stockId") : ""
  },
  mutations: {
    setStockId(state, newStockId) {
      state.stockId = newStockId;
      localStorage.setItem("stockId", newStockId);
    }
  },
  actions: {
  },
  //子模块
  modules: {
    item,
    shoppingCart
  },
  getters: {
    stockId : state => state.stockId,
    storeCode: () => "10001",
    catalogId: () => 3,
    channelCode: () => "trtjkmachine"
  }
})

类似route,store也会注册全局变量$store,供其他模块引用

computed: {
  stockId () {
    return this.$store.getters.stockId
  },
  cartItem() {
    //获取子模块内容
    return this.$store.shoppingCart.getters.items
  }
}

关于vue-cli

这是用于搭建vue项目脚手架的工具,通过npm安装。

npm install -g @vue/cli

通过vue create创建项目

vue create hello-world

通过vue add添加模块

vue add element-ui

配置vue cli

vue-cli配置基于webpack,但是进行了一层封装,说真的封装的不怎么友好。

基本配置可以增加vue.config.js配置。

原文地址:https://www.cnblogs.com/mosakashaka/p/12609252.html