鍍金池/ 問(wèn)答/HTML/ $route.matched報(bào)錯(cuò)

$route.matched報(bào)錯(cuò)

js
const foo = {template:'<div>{{$route.matched}}</div>'}
const bar = {template:'<div>{{$route.fullPath}}</div>'}

const router1 = new VueRouter({
routes: [

// 下面的對(duì)象就是 route record
{ path: '/foo', component: foo,
  children: [
    // 這也是個(gè) route record
    { path: 'bar', component: bar }
  ]
}

]
})

const app = new Vue({

el:'#app',
router:router1

})

html

<!DOCTYPE html>
<html>
<head>

<title>vue-router</title>
<meta charset="utf-8">
<style>
</style>

</head>
<script type="text/javascript" src='vue.js'></script>
<script type="text/javascript" src='vue-router.js'></script>
<body>
<div id='app'>

<h1>hello app!</h1>
<p>
    <router-link to='/foo/bar'>go to foo</router-link>
</p>
<router-view></router-view>

</div>
<script type="text/javascript" src='vueRouter.js'></script>
</body>
</html>

會(huì)報(bào)這樣的錯(cuò)誤
Vue warn: Error in render: "TypeError: Converting circular structure to JSON"

求解

回答
編輯回答
久愛(ài)她

這個(gè)錯(cuò)誤的意思大概是json中有循環(huán)引用,但是為什么會(huì)出現(xiàn)呢?

首先,$router.matched是一個(gè)數(shù)組,然后里面包著對(duì)象,你可以本地輸出$router看看,如果你要在頁(yè)面中輸出這個(gè)數(shù)組的時(shí)候,js會(huì)自動(dòng)幫你轉(zhuǎn)成字符串,也就是使用JSON.stringify()這個(gè)方法,但是當(dāng)js幫你轉(zhuǎn)換的時(shí)候發(fā)現(xiàn),你這個(gè)$router.matched中包含了循環(huán)引用,也就是這個(gè)$router.matched.instance.default.$router等于$router。

舉個(gè)不恰當(dāng)?shù)睦?,比?br>a = { b: a },當(dāng)你要JSON.stringify(a)的時(shí)候就會(huì)輸出"{"b":{"b":{"b":{.......}}}"

而這個(gè)錯(cuò)誤就是為了避免出現(xiàn)這種情況的。

2018年7月17日 09:12