Vue 基本 api

127 阅读7分钟

Vue.js关键字

关键字作用示例
new Vue创建一个新的Vue实例new Vue({ el: '#app', data: { message: 'Hello Vue!' } })
{{ }}插值语法,用于绑定数据到DOM<div>{{ message }}</div>
v-bind动态绑定HTML属性<img v-bind:src="imageSrc">
v-model双向绑定输入控件的数据<input v-model="inputValue">
v-if条件渲染<p v-if="seen">Now you see me</p>
v-for循环渲染列表<li v-for="item in items">{{ item.text }}</li>
v-on事件监听<button v-on:click="doSomething">Click me</button>
v-show基于条件展示元素(元素仍在DOM中)<p v-show="isVisible">You can see me</p>
computed计算属性,用于处理复杂逻辑computed: { reversedMessage() { return this.message.split('').reverse().join(''); } }
watch侦听器,用于监听数据变化watch: { message(newVal, oldVal) { console.log('Message changed from', oldVal, 'to', newVal); } }
created生命周期钩子,实例创建完成时调用created() { console.log('Instance created'); }
mounted生命周期钩子,实例挂载完成时调用mounted() { console.log('Instance mounted'); }
components定义或引入子组件components: { 'my-component': MyComponent }
props父组件传递给子组件的数据props: ['title']
emit子组件向父组件发送事件this.$emit('myEvent')
routes定义路由规则const routes = [{ path: '/home', component: Home }]
router-view路由出口,显示匹配的组件<router-view></router-view>
router-link创建导航链接<router-link to="/home">Go to Home</router-link>
stateVuex中存储应用状态const store = new Vuex.Store({ state: { count: 0 } })
mutations更改状态的方法mutations: { increment(state) { state.count++ } }
actions处理异步操作并提交mutationsactions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
getters从state中派生出需要的状态getters: { doneTodos: state => state.todos.filter(todo => todo.done) }

基本数据类型和数组

以下是包含Vue.js中基本数据类型和数组的关键字、作用以及示例的表格:

关键字作用示例
String字符串数据类型data: { message: 'Hello Vue!' }
Number数字数据类型data: { count: 42 }
Boolean布尔数据类型data: { isActive: true }
Array数组数据类型data: { items: [1, 2, 3, 4, 5] }
Object对象数据类型data: { user: { name: 'John', age: 30 } }

具体的使用示例如下:

基本数据类型

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',  // String
    count: 42,              // Number
    isActive: true,         // Boolean
    user: {                 // Object
      name: 'John',
      age: 30
    }
  }
});

数组

new Vue({
  el: '#app',
  data: {
    items: [1, 2, 3, 4, 5]  // Array
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <p>Count: {{ count }}</p>
      <p v-if="isActive">Active</p>
      <p>User: {{ user.name }}, Age: {{ user.age }}</p>
      <ul>
        <li v-for="item in items">{{ item }}</li>
      </ul>
    </div>
  `
});

集合容器

好的,以下是关于Vue.js中常用的集合容器(例如数组和对象)的关键字、作用及示例的表格:

关键字作用示例
Array存储有序的元素集合,使用索引访问data: { items: [1, 2, 3, 4, 5] }
Object存储键值对的无序集合,使用键访问data: { user: { name: 'John', age: 30 } }
Set存储唯一值的集合data: { uniqueItems: new Set([1, 2, 3]) }
Map存储键值对的集合,键可以是任意类型data: { userMap: new Map([['name', 'John'], ['age', 30]]) }

具体的使用示例如下:

数组

new Vue({
  el: '#app',
  data: {
    items: [1, 2, 3, 4, 5]  // Array
  },
  template: `
    <div>
      <ul>
        <li v-for="item in items">{{ item }}</li>
      </ul>
    </div>
  `
});

对象

new Vue({
  el: '#app',
  data: {
    user: {                 // Object
      name: 'John',
      age: 30
    }
  },
  template: `
    <div>
      <p>User: {{ user.name }}, Age: {{ user.age }}</p>
    </div>
  `
});

集合(Set)

new Vue({
  el: '#app',
  data: {
    uniqueItems: new Set([1, 2, 3])  // Set
  },
  computed: {
    uniqueItemsArray() {
      return Array.from(this.uniqueItems);
    }
  },
  template: `
    <div>
      <ul>
        <li v-for="item in uniqueItemsArray">{{ item }}</li>
      </ul>
    </div>
  `
});

映射(Map)

new Vue({
  el: '#app',
  data: {
    userMap: new Map([['name', 'John'], ['age', 30]])  // Map
  },
  computed: {
    userEntries() {
      return Array.from(this.userMap.entries());
    }
  },
  template: `
    <div>
      <ul>
        <li v-for="(value, key) in userEntries">{{ key }}: {{ value }}</li>
      </ul>
    </div>
  `
});

在这些示例中:

  • items 是一个数组,用于存储有序的元素集合。
  • user 是一个对象,用于存储键值对。
  • uniqueItems 是一个集合(Set),用于存储唯一值。
  • userMap 是一个映射(Map),用于存储键值对,键可以是任意类型。

在Vue.js中,“锁”不是一个标准的概念或内置功能,但在开发中,有时会需要使用“锁”机制来控制异步操作的顺序或避免重复执行某些操作。可以通过多种方式实现类似锁的机制,如使用布尔标志、Promise、或Vuex状态管理来实现。

以下是一些常用方法的示例,展示了如何在Vue.js中实现锁的机制:

使用布尔标志

一个简单的方法是使用布尔标志来控制操作的执行。

new Vue({
  el: '#app',
  data: {
    isLocked: false,  // 锁定标志
    message: 'Ready'
  },
  methods: {
    async performTask() {
      if (this.isLocked) {
        console.log('Task is locked.');
        return;
      }

      this.isLocked = true;
      this.message = 'Task is running...';

      // 模拟异步操作
      await new Promise(resolve => setTimeout(resolve, 2000));

      this.message = 'Task completed';
      this.isLocked = false;
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="performTask">Start Task</button>
    </div>
  `
});

使用Promise

使用Promise来确保某个异步操作只会执行一次,直到操作完成后才允许再次执行。

new Vue({
  el: '#app',
  data: {
    taskPromise: null,
    message: 'Ready'
  },
  methods: {
    performTask() {
      if (this.taskPromise) {
        console.log('Task is already running.');
        return;
      }

      this.message = 'Task is running...';
      this.taskPromise = new Promise(resolve => setTimeout(resolve, 2000))
        .then(() => {
          this.message = 'Task completed';
          this.taskPromise = null;
        });
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="performTask">Start Task</button>
    </div>
  `
});

使用Vuex进行状态管理

使用Vuex来管理全局状态,可以实现更复杂的锁机制,特别是在大型应用中。

// store.js
const store = new Vuex.Store({
  state: {
    isLocked: false,
    message: 'Ready'
  },
  mutations: {
    setLocked(state, payload) {
      state.isLocked = payload;
    },
    setMessage(state, message) {
      state.message = message;
    }
  },
  actions: {
    async performTask({ commit, state }) {
      if (state.isLocked) {
        console.log('Task is locked.');
        return;
      }

      commit('setLocked', true);
      commit('setMessage', 'Task is running...');

      // 模拟异步操作
      await new Promise(resolve => setTimeout(resolve, 2000));

      commit('setMessage', 'Task completed');
      commit('setLocked', false);
    }
  }
});

// main.js
new Vue({
  el: '#app',
  store,
  computed: {
    message() {
      return this.$store.state.message;
    }
  },
  methods: {
    startTask() {
      this.$store.dispatch('performTask');
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="startTask">Start Task</button>
    </div>
  `
});

在这些示例中:

  • 使用布尔标志和Promise都可以简单地控制操作的执行顺序。
  • 使用Vuex可以在大型应用中更灵活地管理状态,确保不同组件间的状态一致性和同步。

并发和异步

在Vue.js开发中,处理并发和异步操作是常见的需求。下面是一些常用方法和示例,展示了如何在Vue.js中处理并发和异步操作。

使用Promise

Promise是处理异步操作的基础,可以链式调用和捕获错误。

new Vue({
  el: '#app',
  data: {
    message: 'Ready'
  },
  methods: {
    async fetchData() {
      this.message = 'Fetching data...';
      try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        this.message = 'Data fetched: ' + JSON.stringify(data);
      } catch (error) {
        this.message = 'Error fetching data: ' + error.message;
      }
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="fetchData">Fetch Data</button>
    </div>
  `
});

使用Async/Await

Async/Await是ES8引入的语法糖,用于简化Promise的使用,使代码看起来更像同步代码。

new Vue({
  el: '#app',
  data: {
    message: 'Ready'
  },
  methods: {
    async fetchData() {
      this.message = 'Fetching data...';
      try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        this.message = 'Data fetched: ' + JSON.stringify(data);
      } catch (error) {
        this.message = 'Error fetching data: ' + error.message;
      }
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="fetchData">Fetch Data</button>
    </div>
  `
});

并发处理

使用Promise.all处理多个并发的异步操作,并在所有操作完成后执行某个动作。

new Vue({
  el: '#app',
  data: {
    message: 'Ready',
    results: []
  },
  methods: {
    async fetchMultipleData() {
      this.message = 'Fetching data...';
      try {
        let [response1, response2] = await Promise.all([
          fetch('https://api.example.com/data1'),
          fetch('https://api.example.com/data2')
        ]);
        let data1 = await response1.json();
        let data2 = await response2.json();
        this.results = [data1, data2];
        this.message = 'Data fetched';
      } catch (error) {
        this.message = 'Error fetching data: ' + error.message;
      }
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <ul>
        <li v-for="result in results">{{ result }}</li>
      </ul>
      <button @click="fetchMultipleData">Fetch Multiple Data</button>
    </div>
  `
});

使用Axios处理并发请求

Axios是一个流行的HTTP客户端库,支持Promise并简化HTTP请求。下面是使用Axios处理并发请求的示例。

// Ensure Axios is included in your project
// npm install axios

import axios from 'axios';

new Vue({
  el: '#app',
  data: {
    message: 'Ready',
    results: []
  },
  methods: {
    async fetchMultipleData() {
      this.message = 'Fetching data...';
      try {
        let [response1, response2] = await Promise.all([
          axios.get('https://api.example.com/data1'),
          axios.get('https://api.example.com/data2')
        ]);
        this.results = [response1.data, response2.data];
        this.message = 'Data fetched';
      } catch (error) {
        this.message = 'Error fetching data: ' + error.message;
      }
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <ul>
        <li v-for="result in results">{{ result }}</li>
      </ul>
      <button @click="fetchMultipleData">Fetch Multiple Data</button>
    </div>
  `
});

使用Vuex处理异步操作

在大型应用中,可以使用Vuex来处理和管理全局的异步操作。

// store.js
const store = new Vuex.Store({
  state: {
    message: 'Ready',
    results: []
  },
  mutations: {
    setMessage(state, message) {
      state.message = message;
    },
    setResults(state, results) {
      state.results = results;
    }
  },
  actions: {
    async fetchMultipleData({ commit }) {
      commit('setMessage', 'Fetching data...');
      try {
        let [response1, response2] = await Promise.all([
          fetch('https://api.example.com/data1').then(res => res.json()),
          fetch('https://api.example.com/data2').then(res => res.json())
        ]);
        commit('setResults', [response1, response2]);
        commit('setMessage', 'Data fetched');
      } catch (error) {
        commit('setMessage', 'Error fetching data: ' + error.message);
      }
    }
  }
});

// main.js
new Vue({
  el: '#app',
  store,
  computed: {
    message() {
      return this.$store.state.message;
    },
    results() {
      return this.$store.state.results;
    }
  },
  methods: {
    fetchMultipleData() {
      this.$store.dispatch('fetchMultipleData');
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <ul>
        <li v-for="result in results">{{ result }}</li>
      </ul>
      <button @click="fetchMultipleData">Fetch Multiple Data</button>
    </div>
  `
});

定义方法和函数

在JavaScript中,定义方法和函数有多种方式。在Vue.js中,方法通常在组件的methods对象中定义,而独立函数可以在组件外部定义和导入。以下是不同场景下定义方法和函数的示例。

定义组件方法

在Vue组件中,方法可以在methods对象中定义,并通过this关键字访问组件的数据和其他方法。

new Vue({
  el: '#app',
  data: {
    count: 0
  },
  methods: {
    increment() {
      this.count += 1;
    },
    decrement() {
      this.count -= 1;
    }
  },
  template: `
    <div>
      <p>Count: {{ count }}</p>
      <button @click="increment">Increment</button>
      <button @click="decrement">Decrement</button>
    </div>
  `
});

定义独立函数

独立函数可以在Vue组件外部定义,然后在组件中导入和使用。

// utils.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

// main.js
import Vue from 'vue';
import { add, subtract } from './utils.js';

new Vue({
  el: '#app',
  data: {
    num1: 5,
    num2: 3
  },
  computed: {
    sum() {
      return add(this.num1, this.num2);
    },
    difference() {
      return subtract(this.num1, this.num2);
    }
  },
  template: `
    <div>
      <p>{{ num1 }} + {{ num2 }} = {{ sum }}</p>
      <p>{{ num1 }} - {{ num2 }} = {{ difference }}</p>
    </div>
  `
});

在类中定义方法

可以在类中定义方法,并在Vue组件中使用类的实例。

// person.js
export class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }

  haveBirthday() {
    this.age += 1;
  }
}

// main.js
import Vue from 'vue';
import { Person } from './person.js';

new Vue({
  el: '#app',
  data: {
    person: new Person('John Doe', 30)
  },
  methods: {
    celebrate() {
      this.person.haveBirthday();
    }
  },
  template: `
    <div>
      <p>{{ person.greet() }}</p>
      <button @click="celebrate">Have Birthday</button>
      <p>{{ person.greet() }}</p>
    </div>
  `
});

使用箭头函数

箭头函数在处理上下文绑定时非常有用,特别是在需要访问外部作用域的this时。

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    showMessage() {
      setTimeout(() => {
        alert(this.message);
      }, 1000);
    }
  },
  template: `
    <div>
      <button @click="showMessage">Show Message</button>
    </div>
  `
});

定义异步方法

在Vue组件中,可以定义异步方法来处理异步操作,例如获取数据或调用API。

new Vue({
  el: '#app',
  data: {
    userData: null,
    error: null
  },
  methods: {
    async fetchUserData() {
      try {
        let response = await fetch('https://api.example.com/user');
        this.userData = await response.json();
      } catch (err) {
        this.error = 'Error fetching user data';
      }
    }
  },
  template: `
    <div>
      <button @click="fetchUserData">Fetch User Data</button>
      <div v-if="error">{{ error }}</div>
      <div v-if="userData">{{ userData.name }}</div>
    </div>
  `
});

OOP

面向对象编程(OOP)是一种编程范式,通过类和对象来组织代码。在Vue.js中,尽管其本身是基于组件的框架,但你仍然可以使用面向对象编程的概念来组织你的业务逻辑。下面是如何在Vue.js中应用OOP的几个示例。

定义类和实例化对象

首先,定义一个简单的类,并在Vue组件中使用这个类。

// 定义一个Person类
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }

  haveBirthday() {
    this.age += 1;
  }
}

// Vue实例
new Vue({
  el: '#app',
  data: {
    person: new Person('John Doe', 30)  // 创建类的实例
  },
  methods: {
    celebrate() {
      this.person.haveBirthday();  // 调用类的方法
    }
  },
  template: `
    <div>
      <p>{{ person.greet() }}</p>
      <button @click="celebrate">Have Birthday</button>
      <p>{{ person.greet() }}</p>
    </div>
  `
});

在类中封装业务逻辑

可以将复杂的业务逻辑封装在类中,然后在Vue组件中实例化和使用这些类。

// 定义一个Task类
class Task {
  constructor(name) {
    this.name = name;
    this.completed = false;
  }

  toggle() {
    this.completed = !this.completed;
  }
}

// Vue组件
new Vue({
  el: '#app',
  data: {
    tasks: [
      new Task('Learn Vue.js'),
      new Task('Build a project'),
      new Task('Deploy to server')
    ]
  },
  methods: {
    toggleTask(task) {
      task.toggle();  // 调用类的方法
    }
  },
  template: `
    <div>
      <ul>
        <li v-for="task in tasks" @click="toggleTask(task)">
          <span :class="{ completed: task.completed }">{{ task.name }}</span>
        </li>
      </ul>
    </div>
  `
});
.completed {
  text-decoration: line-through;
}

继承和多态

通过继承来创建子类,可以复用和扩展父类的功能。

// 定义一个Animal类
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

// 定义一个Dog类,继承自Animal
class Dog extends Animal {
  speak() {
    return `${this.name} barks.`;
  }
}

// Vue组件
new Vue({
  el: '#app',
  data: {
    animals: [
      new Animal('Generic Animal'),
      new Dog('Rover')
    ]
  },
  template: `
    <div>
      <ul>
        <li v-for="animal in animals">{{ animal.speak() }}</li>
      </ul>
    </div>
  `
});

使用组合模式

组合模式是一种更灵活的对象组织方式,相比继承更加松散耦合。

// 定义一个能走路的行为
const canWalk = {
  walk() {
    return `${this.name} is walking.`;
  }
};

// 定义一个能游泳的行为
const canSwim = {
  swim() {
    return `${this.name} is swimming.`;
  }
};

// 定义一个Person类
class Person {
  constructor(name) {
    this.name = name;
  }
}

// 将行为组合到Person对象中
Object.assign(Person.prototype, canWalk, canSwim);

// Vue组件
new Vue({
  el: '#app',
  data: {
    person: new Person('John Doe')
  },
  template: `
    <div>
      <p>{{ person.walk() }}</p>
      <p>{{ person.swim() }}</p>
    </div>
  `
});

使用Vuex进行OOP状态管理

在大型应用中,可以将类与Vuex结合使用,以便在全局状态管理中处理复杂的业务逻辑。

// 定义一个Product类
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  applyDiscount(discount) {
    this.price -= this.price * (discount / 100);
  }
}

// Vuex store
const store = new Vuex.Store({
  state: {
    products: [
      new Product('Laptop', 1000),
      new Product('Phone', 500)
    ]
  },
  mutations: {
    applyDiscount(state, { product, discount }) {
      product.applyDiscount(discount);
    }
  },
  actions: {
    applyDiscount({ commit }, payload) {
      commit('applyDiscount', payload);
    }
  }
});

// Vue组件
new Vue({
  el: '#app',
  store,
  computed: {
    products() {
      return this.$store.state.products;
    }
  },
  methods: {
    applyDiscount(product, discount) {
      this.$store.dispatch('applyDiscount', { product, discount });
    }
  },
  template: `
    <div>
      <ul>
        <li v-for="product in products">
          {{ product.name }}: ${{ product.price }}
          <button @click="applyDiscount(product, 10)">Apply 10% Discount</button>
        </li>
      </ul>
    </div>
  `
});

引入依赖和别的js

在Vue.js项目中,通常需要引入依赖库和其他JavaScript文件来增强功能和组织代码。以下是如何在Vue.js项目中引入依赖和其他JavaScript文件的几种常见方法。

使用Vue CLI创建项目

首先,使用Vue CLI创建一个新项目(如果还没有)。

npm install -g @vue/cli
vue create my-project
cd my-project

引入依赖库

通过npm或yarn安装依赖库,并在Vue组件中引入和使用。

  1. 安装依赖库

    npm install axios
    
  2. 在Vue组件中引入并使用

    <template>
      <div>
        <button @click="fetchData">Fetch Data</button>
        <div v-if="data">{{ data }}</div>
      </div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      data() {
        return {
          data: null,
        };
      },
      methods: {
        async fetchData() {
          try {
            const response = await axios.get('https://api.example.com/data');
            this.data = response.data;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        },
      },
    };
    </script>
    

引入本地JavaScript文件

如果你有自定义的JavaScript文件,需要在Vue组件中使用,可以按以下步骤操作:

  1. 创建一个自定义的JavaScript文件(例如,utils.js):

    // utils.js
    export function greet(name) {
      return `Hello, ${name}!`;
    }
    
  2. 在Vue组件中引入并使用

    <template>
      <div>
        <p>{{ greeting }}</p>
      </div>
    </template>
    
    <script>
    import { greet } from './utils';
    
    export default {
      data() {
        return {
          name: 'Vue.js',
          greeting: '',
        };
      },
      created() {
        this.greeting = greet(this.name);
      },
    };
    </script>
    

使用别名(Alias)

可以在vue.config.js中配置路径别名,以便更方便地引入文件。

  1. 配置路径别名

    // vue.config.js
    const path = require('path');
    
    module.exports = {
      configureWebpack: {
        resolve: {
          alias: {
            '@': path.resolve(__dirname, 'src'),
            '@components': path.resolve(__dirname, 'src/components'),
            '@utils': path.resolve(__dirname, 'src/utils'),
          },
        },
      },
    };
    
  2. 使用路径别名引入文件

    <template>
      <div>
        <p>{{ greeting }}</p>
      </div>
    </template>
    
    <script>
    import { greet } from '@utils/utils';
    
    export default {
      data() {
        return {
          name: 'Vue.js',
          greeting: '',
        };
      },
      created() {
        this.greeting = greet(this.name);
      },
    };
    </script>
    

使用插件

Vue.js有一个插件系统,可以使用插件来扩展功能。

  1. 安装插件(例如,vue-router):

    npm install vue-router
    
  2. 在项目中使用插件

    // src/router/index.js
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    import Home from '@/components/Home.vue';
    import About from '@/components/About.vue';
    
    Vue.use(VueRouter);
    
    const routes = [
      { path: '/', component: Home },
      { path: '/about', component: About },
    ];
    
    const router = new VueRouter({
      routes,
    });
    
    export default router;
    
    // src/main.js
    import Vue from 'vue';
    import App from './App.vue';
    import router from './router';
    
    new Vue({
      router,
      render: h => h(App),
    }).$mount('#app');
    

通过这些方法,你可以在Vue.js项目中引入依赖库和其他JavaScript文件,从而更好地组织代码和扩展功能。

项目目录结构

在Vue.js项目中,合理的目录结构有助于代码的组织和维护。使用Vue CLI创建的项目会生成一个默认的目录结构,以下是一个典型的Vue.js项目目录结构示例,以及每个目录和文件的用途说明。

典型的Vue.js项目目录结构

my-project/
├── node_modules/
├── public/
│   ├── index.html
│   └── favicon.ico
├── src/
│   ├── assets/
│   │   └── logo.png
│   ├── components/
│   │   ├── HelloWorld.vue
│   │   └── ...
│   ├── views/
│   │   ├── Home.vue
│   │   ├── About.vue
│   │   └── ...
│   ├── router/
│   │   └── index.js
│   ├── store/
│   │   └── index.js
│   ├── utils/
│   │   └── utils.js
│   ├── App.vue
│   ├── main.js
│   └── ...
├── .gitignore
├── babel.config.js
├── package.json
├── README.md
├── vue.config.js
└── ...

目录和文件说明

  • node_modules/: 存放项目的所有依赖包,由npm或yarn管理。
  • public/: 存放静态文件,不会经过Webpack处理。index.html是入口文件,favicon.ico是网站图标。
  • src/: 源代码目录,所有的Vue组件、静态资源、路由、状态管理等都放在这里。
    • assets/: 存放静态资源,如图片、样式表等。
    • components/: 存放通用的Vue组件,这些组件可以在多个视图中重用。
    • views/: 存放视图组件(通常是页面级组件),这些组件通常会与路由一一对应。
    • router/: 存放路由配置文件。
      • index.js: 路由的入口文件,定义应用的路由规则。
    • store/: 存放Vuex的状态管理文件。
      • index.js: Vuex的入口文件,配置状态、突变、动作等。
    • utils/: 存放工具函数或辅助类,通常是一些通用的JavaScript函数。
      • utils.js: 示例工具函数文件。
    • App.vue: 根组件,是应用的入口组件。
    • main.js: 应用的入口文件,初始化Vue实例并挂载到DOM上。
  • .gitignore: Git忽略文件配置,定义哪些文件和目录不应该被Git追踪。
  • babel.config.js: Babel配置文件,用于JavaScript的转译。
  • package.json: 项目的配置文件,包含项目的依赖、脚本等信息。
  • README.md: 项目的说明文档。
  • vue.config.js: Vue CLI项目的配置文件,可以对Webpack进行定制化配置。

示例文件内容

src/main.js

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

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

src/router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    // 路由懒加载
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
  },
];

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

export default router;

src/store/index.js

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: 'Hello Vuex',
  },
  mutations: {
    setMessage(state, message) {
      state.message = message;
    },
  },
  actions: {
    updateMessage({ commit }, message) {
      commit('setMessage', message);
    },
  },
  modules: {
    // 其他模块
  },
});

src/utils/utils.js

export function greet(name) {
  return `Hello, ${name}!`;
}

这种目录结构可以根据项目的复杂性和需求进行调整和扩展。通过合理的目录结构,可以使代码更加清晰和易于维护。

路由

在Vue.js中,路由是用于管理单页面应用(SPA)中不同视图之间导航的机制。Vue.js通常使用Vue Router来实现路由功能。以下是关于如何在Vue.js中配置和使用路由的简要说明。

安装和配置 Vue Router

首先,确保已经安装了Vue Router。

npm install vue-router

或者

yarn add vue-router

然后,在Vue项目中,创建一个路由配置文件,通常是在 src/router/index.js 中:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/views/Home.vue';
import About from '@/views/About.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

const router = new VueRouter({
  mode: 'history',
  routes
});

export default router;

使用路由

在Vue组件中,可以通过路由链接 <router-link> 或编程式导航 router.push() 来实现页面之间的切换。

路由链接

在模板中使用 <router-link> 标签来定义路由链接:

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </div>
</template>

编程式导航

在组件中使用 this.$router.push() 方法进行编程式导航:

<script>
export default {
  methods: {
    goToAboutPage() {
      this.$router.push('/about');
    }
  }
}
</script>

嵌套路由

Vue Router 支持嵌套路由,可以在路由配置中嵌套定义子路由:

const routes = [
  { 
    path: '/products', 
    component: Products,
    children: [
      { path: 'laptops', component: Laptops },
      { path: 'phones', component: Phones }
    ]
  }
];

动态路由

Vue Router 支持动态路由,可以通过参数传递数据到路由:

const routes = [
  { path: '/user/:id', component: User }
];

在组件中,可以通过 $route.params 访问动态路由参数。

导航守卫

Vue Router 提供了导航守卫,可以在路由切换前后执行一些逻辑。常见的导航守卫包括 beforeEachbeforeResolveafterEach

router.beforeEach((to, from, next) => {
  // 在路由切换前执行逻辑
  next();
});

懒加载路由

为了提高性能,可以将路由组件进行懒加载,只有在路由被访问时才加载组件:

const About = () => import(/* webpackChunkName: "about" */ '../views/About.vue');

通过以上方式,你可以配置和使用Vue Router来管理你的Vue.js项目中的路由,实现页面间的导航和控制。

项目代理,编译,运行,部署dev,测试,生产环境

在Vue.js项目中,配置代理、编译、运行和部署是常见的操作。以下是如何在开发、测试和生产环境中进行这些操作的详细说明。

配置代理

在开发环境中,可以使用Vue CLI提供的代理功能解决跨域问题。可以在vue.config.js中配置代理:

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000', // 目标服务器地址
        changeOrigin: true,
        pathRewrite: { '^/api': '' } // 路径重写
      }
    }
  }
};

编译

Vue CLI提供了不同环境下的编译命令:

  1. 开发环境

    npm run serve
    

    或者

    yarn serve
    
  2. 测试环境和生产环境

    你可以在package.json中配置不同环境下的编译命令:

    {
      "scripts": {
        "serve": "vue-cli-service serve",
        "build:dev": "vue-cli-service build --mode development",
        "build:test": "vue-cli-service build --mode test",
        "build:prod": "vue-cli-service build --mode production"
      }
    }
    
  3. 自定义环境配置

    创建不同环境的配置文件,例如:.env.development.env.test.env.production

    .env.development:

    VUE_APP_API_URL=http://localhost:5000/api
    

    .env.test:

    VUE_APP_API_URL=http://testserver.com/api
    

    .env.production:

    VUE_APP_API_URL=http://productionserver.com/api
    

运行

在开发环境中,可以通过以下命令启动项目:

npm run serve

或者

yarn serve

在测试和生产环境中,可以通过以下命令编译项目:

npm run build:test
npm run build:prod

编译完成后,可以使用静态文件服务器预览项目,例如serve

npx serve -s dist

部署

将编译生成的静态文件部署到服务器上。以下是几种常见的部署方式:

  1. 静态托管服务

    使用Netlify、Vercel、GitHub Pages等静态托管服务。

  2. 自己搭建服务器

    使用Nginx或Apache部署静态文件。

    Nginx配置示例

    server {
        listen 80;
        server_name yourdomain.com;
    
        location / {
            root /path/to/your/dist;
            try_files $uri $uri/ /index.html;
        }
    
        location /api {
            proxy_pass http://backendserver.com;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
  3. 使用云服务提供商

    使用AWS、Azure、Google Cloud等云服务提供商。

  4. Docker容器化部署

    将Vue.js项目容器化,并使用Docker部署。

    Dockerfile示例

    # Build stage
    FROM node:14 as build-stage
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    RUN npm run build
    
    # Production stage
    FROM nginx:alpine
    COPY --from=build-stage /app/dist /usr/share/nginx/html
    EXPOSE 80
    CMD ["nginx", "-g", "daemon off;"]
    

    构建和运行Docker容器

    docker build -t my-vue-app .
    docker run -p 80:80 my-vue-app
    

通过这些步骤,可以在开发、测试和生产环境中配置、编译、运行和部署Vue.js项目。