vue-cli3 创建项目,路由,数据管理

2019-08-28  本文已影响0人  栗子daisy

安装脚手架

npm install -g @vue/cli
npm install -g @vue/cli-service-global

创建项目

vue create [proName]
npm run serve / yarn serve

link C:\Users\lys\AppData\Roaming\npm\vue@ -> C:\Users\lyys\AppData\Roaming\npm\node_modules\@vue\cli\bin\vue.js

路由

https://cloud.tencent.com/developer/article/1328276

vue-router

yarn add vue-router --save-dev

+ src/router/index.js
import Vue from "vue";
import Router from "vue-router";
import HelloWorld from "@/components/HelloWorld";
import Home from "@/components/Home"
Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/",
      name: "HelloWorld",
      component: HelloWorld
    },{
        path: "/home",
        name: "Home",
        component: Home
      }
  ]
});

// main.js
import Vue from 'vue'
import App from './App.vue'
+ import router from './router'
Vue.config.productionTip = false

new Vue({
 + router,
  render: h => h(App),
}).$mount('#app')

// App.vue
<template>
  <div id="app">
    <p>
    <!-- router-link 组件导航.  `to` 属性指定链接. 渲染成`<a>` 标签 -->
    <router-link to="/">Main</router-link>
     <!-- 建议使用nameMap表进行命名路由的匹配 -->
    <router-link :to="{name:'Home'}" event="mouseover">Home</router-link>
    </p>
  <!-- 路由出口 : 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
  </div>
</template>

状态管理

yarn add vuex

//支持浏览器没有实现Promise(例如IE),您可以使用polyfill

yarn add es6-promise

+ /src/store/index.js
import Vue from "vue";
import Vuex from "vuex";
import "es6-promise/auto";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 1
  },
  // Getter相当于vue中的computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
  getters: {
    getStateCount: function(state) {
      return state.count + 1;
    }
  },
  // 修改store中的值唯一的方法:mutation
  mutations: {
    increment(state) {
      state.count++;
    },
    decrease(state) {
      state.count--;
    }
  }
});
export default store;
src/main.js
import Vue from 'vue'
import App from './App.vue'
+ import store from './store'

Vue.config.productionTip = false

new Vue({
+  store, //vue实例全局引入store对象
  render: h => h(App),
}).$mount('#app')
XX.vue
<template>
  <div class="hello">
     <h1>{{msg}}</h1>
     <div>{{ this.$store.state.count }}</div>
     <div>{{this.$store.getters.getStateCount }}</div>
     <button @click="incremeFunc">+</button>
     <button @click="decreFunc">-</button>
 </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods:{
    incremeFunc(){
      this.$store.commit("increment")
    },
    decreFunc(){
      this.$store.commit("decrease")
    }
  }
}
</script>

上一篇下一篇

猜你喜欢

热点阅读