search
HomeWeb Front-endJS TutorialHow to achieve front-end and back-end separation in Vue project in node

How to achieve front-end and back-end separation in Vue project in node

Jun 20, 2018 pm 06:13 PM
nodenodejsvuevue.jsSeparation of front and back ends

In fact, there are many open source blog systems built based on vue.js node.js. The following article mainly introduces you to the relevant information about back-end separation before the development of node vue project. The article introduces it in detail through sample code. It has certain reference and learning value for everyone's study or work. Friends who need it can come and take a look below.

Preface

This article mainly introduces the relevant information about the separation of node vue front-end and back-end, and shares it for everyone’s reference and study. Below, follow the small Let’s learn together.

node vue project development

I have recently watched vue development for nearly a week and have many feelings. I have been exposed to react and angular before, so it is particularly special. I want to learn Vue, which I have admired for a long time. After studying for a long time, I found that it is much easier to learn as I have come into contact with more things. I can associate the instructions of Vue with the instructions of Angular. The component design of Vue is similar to the component design of React, including some router settings and React. The routes in nodejs or nodejs are similar, and vuex is rewritten based on redux and flux. Although I still don’t understand how to use it, as for vue’s template rendering, it is not much different from express rendering ejs. Using vue can completely break away from jq. Although I haven't felt any magical advantages of not using jq, I think this two-way data binding is quite convenient. This document is used to record some new knowledge I learned about vue. and ideas.

Command

  • v-bind is mainly used to dynamically bind DOM element attributes, that is, the actual value of the element attribute It is provided by the data attribute in the vm instance.

  • v-model mainly performs two-way data binding on form elements. When the value of the form element is modified, the corresponding attributes of the corresponding vm in the instance vm are also updated at the same time.

  • v-if, v-show, v-else instructions illustrate the logical relationship between templates and data
    The function of v-if and v-else is to determine whether to output the dom element and the contained sub-elements based on the numerical value.
    eg:
    <p v-if="yes">yes</p> When data.yes=true in the vm instance, the template engine will compile This dom node outputs <p>yes</p>It is worth noting that v-else must follow v-if, otherwise it will not work.
    The effects of v-show and v-if are similar. They both display content by judging whether it is true or false. The only difference is that when v-show is not displayed, it is display:none, which means that the dom node is retained. But v-if doesn't.

  • v-for is used for list rendering and can loop through arrays and objects. Note that v-for="b in 10" currently refers to 1-10 Iteration

  • v-on event binding, abbreviated @:

  • v-text <p v-text=" msg"></p> <p></p> is equivalent to innerText. Compared with {{msg}}, it avoids the flashing problem.

  • v-HTML is similar to innerHTML, and can also avoid flashing

  • v-el This command is equivalent to adding an index to the dom element. For example <p v-el="demo">this is a test </p>, if you want to get the value in the current dom, you can vm.$els.demo.innerText , Note: HTML is not case-sensitive. Camel case writing will be automatically converted to lower case. You can use - to convert it to upper case.

  • v-ref is similar to v-el and accessed through vim.$refs

  • v-pre skips compilation This element

  • v-cloak feels useless

  • v-once has added built-in instructions to indicate that the element or component will only be rendered once .

Template rendering

1. v-for is mainly used for list rendering, repeating based on the received array Render the dom element and internal sub-elements bound to v-for, and obtain the data in the array and render it into the node by setting an alias.

eg:

 <ul v-for="item in items">
 <li>{{item.title}}</li>
 <li>{{item.description}}</li>
 </ul>

2. v-for has a built-in $index variable, which can be called when calling v-for, for example, <li v- for="(index,item) in items">{{index}}-{{$index}}</li>

3. Modify data

directly Modifying the array can change the data

Case in which the array cannot be changed directly

1.vm.items[0]={} , In this case, it cannot be modified. Solution: vm.item.$set(0,{})or vm.$set('item[0]',{})

2.vm.item.length=0

4. v-for traverses objects and you can customize key variables in the form of (key, value).

<li v-for="(key,value)" in objectDemo>
 {{key}}---{{$key}}:{{vue}}
</li>

5. The template tag

is used as a node for template rendering, but this node does not exist when rendered

Event binding and monitoring

v-on can bind the methods in the instance attribute methods as event handlers, v-on: can later accept all native event names.

  • Abbreviation @:

  • can bind methods functions and also supports inline js, but is limited to one statement.

  • 绑定methods函数和内联js都可以获取原生dom元素,event.

  • 绑定多个事件时,为顺序执行。

ui组件 饿了吗

使用指南

安装

npm install cnpm install element-ui --save-dev

引入文件main.js

import ElementUI from &#39;element-ui&#39;
import &#39;element-ui/lib/theme-chalk/index.css&#39;
Vue.use(ElementUI, { size: &#39;small&#39; })

使用

在components文件夹下新建一个页面,从饿了吗找到自己喜欢的组件,比如走马灯 Carousel.vue 把代码复制到这个页面

在需要的此组件的文件下,比如APP.vue里

import Carousel from &#39;./components/Carousel&#39;
export default {
 name: &#39;app&#39;,
 components: { //components加s
 Carousel: Carousel
 }
}

在模板里载入组件

<template>
<p id="app">
 <Carousel></Carousel>
 <img  src="/static/imghwm/default1.png"  data-src="./assets/logo.png"  class="lazy"   alt="How to achieve front-end and back-end separation in Vue project in node" >
 <router-view/>
</p>
</template>

这样就可运行了

前后端分离

习惯了用node做全栈开发,现在用vue-webpack做前端开发,node做后端开发也挺爽的,前后端实现了分离。

启动后端接口

cd back
cnpm install
npm run dev

启动前端服务器

cd front
cnpm install
npm start

进入登录页面,点击登录,控制台打印访问成功的信息,并成功跳转到helloworld页面

前后端通信

vue-resource

安装vue-resource 并在main.js中引用

import VueResource from &#39;vue-resource&#39;
Vue.use(VueResource)

在config/index.js 配置 proxyTable代理服务器

proxyTable: {
 &#39;/api/**&#39;: {
 target: &#39;http://localhost:3000&#39;,
 pathRewrite: {
 &#39;^/api&#39;: &#39;/api&#39;
 }
 }
}

使用

this.$http.get(&#39;api/apptest&#39;)
 .then((response) => {
  // 响应成功回调
  console.log(response)
 }).catch(e => {
  // 打印一下错误
  console.log(e)
 })
 }

缺点:在开发环境下没有问题,但是在生产环境下请求后端接口不成功

axios

首先配置axios,在src下新建一个http.js

import axios from ‘axios&#39;
axios.defaults.timeout = 5000
axios.defaults.baseURL = &#39;http://localhost:3000&#39;
axios.defaults.headers.post[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;
export default axios

在main.js中引入

import axios from &#39;./http&#39;
Vue.prototype.axios = axios
new Vue({
 el: &#39;#app&#39;,
 router,
 axios,
 template: &#39;<App/>&#39;,
 components: { App }
})

使用

get方法

login () {
 // 获取已有账号密码
 this.axios.get(&#39;/apptest&#39;)
 .then((response) => {
 // 响应成功回调
 console.log(response)
 // this.$router.go({name: &#39;main&#39;})// 不管用
 this.$router.push({name: &#39;HelloWorld&#39;})
 }).catch(e => {
 // 打印一下错误
 console.log(e)
 })
}

post方法

register () {
 console.log(this)
 // 获取已有账号密码
 let params = {
 user: this.userinfo.account,
 password: this.userinfo.password,
 directionId: this.userinfo.directionId
 }
 this.axios.post(&#39;/signup&#39;, params)
 .then((response) => {
 // 响应成功回调
 console.log(response)
 }).catch(e => {
 // 打印一下错误
 console.log(e)
 })
}

生产环境路径问题

在生产环境下发现打包以后路径不对,修改config下的index.js

build: {
 // Template for index.html
 index: path.resolve(__dirname, &#39;../dist/index.html&#39;),

 // Paths
 assetsRoot: path.resolve(__dirname, &#39;../dist&#39;),
 assetsSubDirectory: &#39;static&#39;,
 assetsPublicPath: &#39;./&#39;, //原来是 assetsPublicPath: &#39;/&#39;

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在JS中如何实现网页自动秒杀点击(详细教程)

在node中如何实现http小爬虫

在angular2中有关Http请求原理(详细教程)

使用VueAwesomeSwiper容易出现的问题?

使用Node.js爬虫如何实现网页请求

如何使用VUE2.X过滤器

The above is the detailed content of How to achieve front-end and back-end separation in Vue project in node. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft