1. Vue基础入门

1.1. 1.Vue的安装与使用

1.1.1. 1.1 直接使用<script>引入

直接下载并用 <script> 标签引入,Vue 会被注册为一个全局变量。

在开发环境下不要使用压缩版本,不然你就失去了所有常见错误相关的警告!

CDN

对于制作原型或学习,你可以这样使用最新版本:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

对于生产环境,我们推荐链接到一个明确的版本号和构建文件,以避免新版本造成的不可预期的破坏:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>

如果你使用原生 ES Modules,这里也有一个兼容 ES Module 的构建文件:

<script type="module">
  import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.esm.browser.js'
</script>

你可以在 cdn.jsdelivr.net/npm/vue 浏览 NPM 包的源代码。

Vue 也可以在 unpkgcdnjs 上获取 (cdnjs 的版本更新可能略滞后)。

请确认了解不同构建版本并在你发布的站点中使用生产环境版本,把 vue.js 换成 vue.min.js。这是一个更小的构建,可以带来比开发环境下更快的速度体验。

运行vue等技术开发的客户端项目,需要安装Node.js环境

1.1.2. 1.2 安装Node.js环境

可以到nodejs的下载页面: http://nodejs.cn/download/下载对应的安装包

1.Windows电脑安装Nodejs环境

  • 1、windows环境下选择.msi安装文件。然后进行双击node.msi,选择安装路径。

  • 2、配置环境变量。在计算机(或者我的电脑)右击属性 -> 高级系统设置 -> 环境变量进行配置。新建NODE_PATH变量并设置Nodejs的安装目录。

2.Linux系统安装Nodejs

在nodejs的下载页面选择linux类别下的64位文件,下载文件为tar.xz格式的压缩文件。然后依次执行解压缩和建立软连接的命令:

tar -xvf node-v10.15.3-linux-x64.tar.xz
vi /etc/profile
export NODEJS=/opt/node/node-v10.15.3-linux-x64
export PATH=$NODEJS/bin:$PATH

// 保存/etc/profile文件后
node -v
// 看版本

npm设置切换源

1.查看当前源
npm config get registry

2.设置淘宝源淘宝镜像
npm config set registry https://registry.npm.taobao.org

3.设置官方镜像
npm config set registry https://registry.npmjs.org

1.1.3. 1.3 安装脚手架工具vue-cli

新版本的脚手架包名称由vue-cli改成了@vue/cli。

如果已经全局安装了旧版本的vue-cli(1.x或2.x),

需要先通过如下命令进行卸载

npm uninstall vue-cli -g

yarn global remove vue-cli

安装@vue

CLI(@vue/cli)是一个全局安装的NPM包,提供了终端里使用的Vue命令。它可以通过vue create命令快速创建一个新项目的脚手架,或者直接通过vue serve命令构建新想法的原型。也可以使用vue ui命令,通过一套图形化界面管理你的所有项目。

npm config set registry https://registry.npm.taobao.org/
npm install -g @vue/cli
或者
yarn global add @vue/cli

1.1.4. 1.4 安装webpack

npm install -g webpack
/Users/youmen/.nvm/versions/node/v10.14.2/bin/webpack -> /Users/youmen/.nvm/versions/node/v10.14.2/lib/node_modules/webpack/bin/webpack.js
+ webpack@5.4.0
added 82 packages from 122 contributors in 6.878s


\W $ vue init webpack myvue

? Project name helloworld
? Project description student vue demo1
? Author youmen@163.com
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has
been created? (recommended) npm


安装中有个选项(Use ESLint to line your code? 选择No)

进入myVue,使用npm install 安装package.json中的依赖
cd myVue
npm install

运行项目
npm run dev

1.1.5. 1.5 安装nvm

管理node版本,非必须

// mac
git clone https://github.com/nvm-sh/nvm.git
cd nvm
./install.sh

cat ~/.bash_profile
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

// 换源
export NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node
export NVM_IOJS_ORG_MIRROR=http://npm.taobao.org/mirrors/iojs

source ~/.bash_profile
nvm --version
0.37.0

// 安装指定版本
nvm install 10.14.2

1.1.6. 1.6 安装yarn

Yarn 是 Facebook 发布的 node.js 包管理器,它比 npm 更快、更高效,可以使用 Yarn 替代 npm 。

如果你安装了node,就安装了npm,可以使用下面的命令来安装:

npm i yarn -g --verbose

npm官方源访问速度实在不敢恭维,建议使用之前切换为淘宝镜像,在yarn安装完毕之后执行如下指令:

yarn config set registry https://registry.npm.taobao.org

yarn设置和切换源

1.查看当前源
yarn config get registry

2.修改yarn源为taobao源
yarn config set registry https://registry.npm.taobao.org/

3.设置官方镜像
yarn config set registry https://registry.yarnpkg.com

到此为止我们就可以在项目中像使用npm一样使用yarn了。

使用 Yarn 跟 npm 差别不大,具体命令关系如下:

npm install  => yarn install
npm install --save [package] => yarn add [package]
npm install --save-dev [package] => yarn add [package] --dev
npm install --global [package] => yarn global add [package]
npm uninstall --save [package] => yarn remove [package]
npm uninstall --save-dev [package] => yarn remove [package]

1.2. 2. 创建vue项目

vue create ginessentail-vue
Vue CLI v4.5.8
? Please pick a preset: (Use arrow keys)
  Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
❯  Manually select features




Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project:
 ◉ Choose Vue version
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
❯◯ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing



Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, Lin
ter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) (Y/n) y




Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
):
  Sass/SCSS (with dart-sass)
❯ Sass/SCSS (with node-sass)
  Less
  Stylus



Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): Sass/SCSS (with node-sass)
? Pick a linter / formatter config:
  ESLint with error prevention only
❯ ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier



Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Airbnb
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
  In package.json


success Saved lockfile.
✨  Done in 17.00s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.22.10
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
✨  Done in 8.86s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project ginessentail-vue.
👉  Get started with the following commands:

 $ cd ginessentail-vue
 $ yarn serve

cd ginessentail-vue
yarn serve

引入bootstrap

yarn add vue bootstrap-vue bootstrap

1.3. 3.创建一个Vue实例

index.html文件代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <!-- 引入vue框架 -->
        <script src="js/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <p>姓名:{{name}}</p>
            <p>年龄:{{age}}</p>
        </div>
        <script type="text/javascript">
            // 创建vue实例
            new Vue({
                el: '#app',
                data: {
                    name: 'hujianli',
                    age: 18
                }
            })
        </script>
    </body>
</html>

1.4. 4.Vue模板语法

1.4.1. 4.1 插值

1.文本

数据绑定最常见的形式就是使用Mustache语法(双大括号)的文本插值,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <!-- 引入vue框架 -->
        <script src="js/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <h2>欢迎大家学习{{message}}这本书</h2>
        </div>
        <script type="text/javascript">
            // 创建vue实例
            new Vue({
                el: '#app',
                data: {
                    message: "《Vue企业开发实战》"
                }
            })
        </script>
    </body>
</html>

2.原始HTML

双大括号会将数据解释为普通文本,而非HTML代码。为了输出真正的HTML,我们需要使用v-html指令。

如果想要在页面中输出一个超链接,我们先在data属性中声明一个值,其含有标签的字符串属性,然后使用v-html指令绑定到对应的HTML元素上,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div id="app">
            <!-- 基础指令 -->
            <div v-text="message">{{message}}</div>
            <div v-html="message"></div>
        </div>
        <script type="text/javascript">
            new Vue({
                el: '#app',
                data: {
                    message: '<a href="http://cn.vuejs.org">vue.js官网</a>'
                }
            })
        </script>
    </body>
</html>

3.使用JavaScript表达式

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div id="app">
            <!-- 模板输出 -->
            <div>{{msg}}</div>
            <div>{{message}}</div>
            <div v-html="message"></div>

            <!-- JS表达式输出 -->
            <div>{{ number + 1 }}</div>
            <div>{{ ok ? 'YES' : 'NO' }}</div>
            <div>{{ number + 1 }}</div>
            <div>{{ msg.split('').reverse().join('') }}</div>
        </div>
        <script type="text/javascript">
            new Vue({
                el: '#app',
                data: {
                    number: 1,
                    msg: 'hello world',
                    message: '<a href="http://cn.vuejs.org">vue.js官网</a>',
                    ok: true,
                }
            })
        </script>
    </body>
</html>

1.4.2. 4.2 指令

指令(directives)是带有“v-”前缀的特殊属性,指令设计的初衷是用于表示单个的JavaScript表达式(v-for为例外情况)。指令的作用是当表达式的值发生改变时,可以动态地将结果响应式作用在DOM元素上,代码如下:

<p v-if="seen">这里是要显示的内容</p>

1.v-bind缩写

<!--    完整语法-->
    <a v-bind:href="url">百度</a>
<!--    缩写-->
    <a :href="url">百度</a>
<!--    动态参数缩写-->
    <a :[key]="url">百度</a>

2.v-on缩写

<!--    <button v-on:click="jump">单击弹窗</button>-->

<!--    简写,一般多使用简写-->
<button @click="jump">单击弹窗</button>