1. 程式人生 > >vue 項目搭建 及基礎介紹

vue 項目搭建 及基礎介紹

fun ins rom 視圖組件 component 搭建 display response type

一、Vue-CLI項目搭建

1、環境搭建

a、安裝node

官網下載安裝包,傻瓜式安裝:https://nodejs.org/zh-cn/

b、安裝cnpm

npm install -g cnpm --registry=https://registry.npm.taobao.org

c、安裝腳手架

cnpm install -g @vue/cli

d、清空緩存處理

npm cache clean --force

2、項目的創建

a、創建項目

vue creat 項目名
// 要提前進入目標目錄(項目應該創建在哪個目錄下)
// 選擇自定義方式創建項目,選取Router, Vuex插件

b、啟動/停止項目

npm run serve / ctrl+c
// 要提前進入項目根目錄

c、打包項目

npm run build
// 要在項目根目錄下進行打包操作

3、認識項目

a、項目目錄

dist: 打包的項目目錄(打包後會生成)
node_modules: 項目依賴
public: 共用資源
src: 項目目標,書寫代碼的地方
    -- assets:資源
    -- components:組件
    -- views:視圖組件
    -- App.vue:根組件
    -- main.js: 入口js
    -- router.js: 路由文件
    
-- store.js: 狀態庫文件 vue.config.js: 項目配置文件(沒有可以自己新建)

b、配置文件:vue.config.js

module.exports={
    devServer: {
        port: 8888
    }
}
// 修改端口,選做  也可以通過編輯器ide來修改

c、main.js (主要的配置文件)

new Vue({
    el: "#app",
    router: router,
    store: store,
    render: function (h) {
        
return h(App) } })

d、.vue文件(有三部份組成)

技術分享圖片
<template>
    <!-- 模板區域 -->
</template>
<script>
    // 邏輯代碼區域
    // 該語法和script綁定出現
    export default {
        
    }
</script>
<style scoped>
    /* 樣式區域 */
    /* scoped表示這裏的樣式只適用於組件內部, scoped與style綁定出現 */
</style>
View Code

二、Vue項目操作

1、創建一個組件:

-創建一個course.vue
-配置路由:route.js中
    import Course from ‘./views/Course.vue‘  // 導入組件
    
{
    path: ‘/course‘,
    name: ‘course‘,
     component:Course  # 給組建配置路由
    }
-<router-link to="/course">免費課程</router-link>  // 實現路由跳轉

2、顯示數據:

-在組件的script部分中:
    data:function () {
        return{
            courses:[‘python‘,‘linux‘,‘java‘],  // 數據必須放在return中
        }
    }
-在template中就可以使用retrun的變量
    -{{courses}}
    -用v-for顯示數據
        <ul>
          <li v-for="course in courses">{{course}}</li> 
        </ul>

3、用axios實現與後臺交互:

a、axios的安裝

axios  vue的ajax
-安裝: 在Terminal中輸入 npm install axios 執行,

// 組件中:數據渲染
// template:
<button @click="init">點我</button> // 讓button跟init方法綁定
// script
methods: {
    init: function () {
        // 向後臺發送請求,加載數據
        alert(1)
    },
    }

b、axios實現與後臺進行數據交互

// axios的使用
    // main.js加上以下兩句
        // 導入axios
        import axios from ‘axios‘
        // 相當於放到全局變量中
        Vue.prototype.$http=axios
    // 在組件中使用(script中,一般在方法中寫)  鏈式書寫方式
        this.$http.request({
            url:‘請求的地址‘,
            method:‘請求方式‘
        }).then(function(response){
            // 請求成功會回調該匿名函數
            // 取實際返回的值response.data中取

        }).catch(function (error) {
            // 請求出現錯誤,回調該方法
        })

三、element-ui的安裝及使用

1、安裝element-ui

安裝 npm i element-ui -S/
cnpm i element-ui -S

2、element-ui的使用

// 使用:
    // 1 在main.js中
        import ElementUI from ‘element-ui‘;
        import ‘element-ui/lib/theme-chalk/index.css‘;
        Vue.use(ElementUI);
    // 2 從官網上copy代碼,粘貼,修改
// 圖片綁定
    // item是js中的一個變量 一定要在src前添上冒號(相當於v-bind:)進行綁定
    <img :src="item" >

vue 項目搭建 及基礎介紹