How to achieve front-end and back-end separation in Vue project in node
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>
Whendata.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 isdisplay: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 Iterationv-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 canvm.$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 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI, { size: 'small' })
使用
在components文件夹下新建一个页面,从饿了吗找到自己喜欢的组件,比如走马灯 Carousel.vue
把代码复制到这个页面
在需要的此组件的文件下,比如APP.vue里
import Carousel from './components/Carousel' export default { name: 'app', 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 'vue-resource' Vue.use(VueResource)
在config/index.js 配置 proxyTable代理服务器
proxyTable: { '/api/**': { target: 'http://localhost:3000', pathRewrite: { '^/api': '/api' } } }
使用
this.$http.get('api/apptest') .then((response) => { // 响应成功回调 console.log(response) }).catch(e => { // 打印一下错误 console.log(e) }) }
缺点:在开发环境下没有问题,但是在生产环境下请求后端接口不成功
axios
首先配置axios,在src下新建一个http.js
import axios from ‘axios' axios.defaults.timeout = 5000 axios.defaults.baseURL = 'http://localhost:3000' axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' export default axios
在main.js中引入
import axios from './http' Vue.prototype.axios = axios new Vue({ el: '#app', router, axios, template: '<App/>', components: { App } })
使用
get方法
login () { // 获取已有账号密码 this.axios.get('/apptest') .then((response) => { // 响应成功回调 console.log(response) // this.$router.go({name: 'main'})// 不管用 this.$router.push({name: 'HelloWorld'}) }).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('/signup', params) .then((response) => { // 响应成功回调 console.log(response) }).catch(e => { // 打印一下错误 console.log(e) }) }
生产环境路径问题
在生产环境下发现打包以后路径不对,修改config下的index.js
build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: './', //原来是 assetsPublicPath: '/'
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!

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.

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.

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 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

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.

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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
