amenzai / myDiary

Record what you do every day
4 stars 0 forks source link

vue碎碎谈 #1

Open amenzai opened 6 years ago

amenzai commented 6 years ago

1. vue-cli创建项目结构

  1. 装node(npm包含其中) 使用node -v npm -v 验证是否安装成功
  2. 全局安装vue-cli npm install -g vue-cli 嫌慢的话,安装cnpmnpm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install -g vue-cli
  3. 初始化项目 vue init webpack vue-demo cd vue-demo npm install or cnpm install
  4. 启动项目 npm run dev

2. vue-router页面跳转

记住这些用于页面跳转的:

2.1 router-link

<router-link :to="'/home/:id'"></router-link>
<router-link :to="{path:'/home/login',query:{name:'tom'}}"></router-link>
<router-link :to="{path:'/home/login',params:{id:1}}"></router-link>

2.2 $router.push

//参数可以是字符串或对象
this.$router.push()

3. vuex

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state,
  mutations: {
    UPDATE_LOADING(state, status) {
      state.loading = status
    }
  },
  actions: {
    ToggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    addVisitedViews({ commit }, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])
      })
    }
  }
})

4. axios处理异步请求

查看详细教程

5. 组件之间数据传递

父组件向子组件:props props:['data'] 子组件向父组件:父组件自定义事件,子组件$emit触发事件 this $emit('eventName',data)

6. 其他

keep-alive 将组件保留在内存中,避免重新渲染 slot在子组件设置个插槽,这样父组件在调用时可以用其他结构替换。 子组件中:

<slot name="btn"></slot>

父组件:

<children-component>
  <button slot="btn"></button>
</children-component>