码迷,mamicode.com
首页 > 其他好文 > 详细

vue

时间:2019-05-20 19:30:06      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:create   round   初始化   eve   listening   ase   初始   ext   div   

vue的history模式实现原理   运行 node index.js 

html

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>history</title>
</head>
<body>
vue-router的 history模式代码
<a href="/">index</a>
<a href="/about">about</a>

<div id="router-view"></div>
<script>
    let a_s= document.querySelectorAll(a)
    let routerView = document.getElementById(router-view)

    // 内容渲染
    function changeContent(href){
      switch(href){
        case /:
          routerView.innerHTML=`<div>首页</div>`
          break;
        case /about:
          routerView.innerHTML=`<div>about</div>`
          break;
      }
    }
    changeContent(location.pathname)  // init   这里要处理一下才可以
    // 点击
    Array.from(a_s).forEach(val=>{
      val.addEventListener(click,function (e) {
        e.preventDefault()
        let href = e.target.getAttribute(href)
        history.pushState({},history,href) // 只变动地址栏,真正的页面跳转要另外处理
        changeContent(href)  // 渲染内容
      })
    })
</script>
</body>
</html>
View Code

index.js

技术图片
// 代码来自 vue-router history模式 ,读取html,并返回html
// 解决  localhost/about 初始化内容渲染
const http = require(‘http‘)
const fs = require(‘fs‘)
const httpPort = 80

http.createServer((req, res) => {


  fs.readFile(‘./0.html‘, ‘utf-8‘, (err, content) => {
    if (err) {
      console.log(‘We cannot open "index.htm" file.‘)
    }

    res.writeHead(200, {
      ‘Content-Type‘: ‘text/html; charset=utf-8‘
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log(‘Server listening on: http://localhost:%s‘, httpPort)
})
View Code

 

vue

标签:create   round   初始化   eve   listening   ase   初始   ext   div   

原文地址:https://www.cnblogs.com/gyz418/p/10895726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!