首页 > 解决方案 > 为什么 Vue.js 实例在 Firefox 扩展开发中不起作用?

问题描述

清单.json:

{

  "manifest_version": 2,
  "name": "Vue",
  "version": "1.0",

  "description": "Vue Test",

  "icons": {
    "96": "icons/icon.png"
  },

  "permissions": [
    "tabs"
  ],

  "background": {
    "scripts": ["background.js"]
  },
  
  "browser_action": {
    "default_icon": "icons/icon.png",
    "default_title": "Vue"
  }
}

背景.js:

browser.browserAction.onClicked.addListener(()=>{
    browser.tabs.create({url: 'index.html'})
       .then(()=>browser.tabs.executeScript({file: "index.js"}))
       .then(()=>browser.tabs.executeScript({file: "vue.js"}))
})

索引.html:

<!DOCTYPE html>
<html>

<head>
    <title>Vue</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="index.css"/>
</head>

<body>

    <div id="app">{{msg}}</div>
    
    <script src="vue.js"></script>
    <script src="index.js"></script>
</body>

</html>

vue.js:从 vue 页面下载的 vue.js 本身

index.js:

let app = new Vue({
  el: '#app',
  data: {
    msg: 'hi'
  }
})

问题:屏幕上没有呈现任何内容。如果我得到相同的 index.html 并直接在浏览器上打开它,它将呈现消息“hi”。我错过了什么?

标签: javascriptvue.jsfirefox-addon

解决方案


首先,vue.js不需要index.jsindex.html文件中再次导入,因为它已经从background.js.

其次,应该首先执行 in background.jsvue.js以便 VueJS 稍后准备好初始化主应用程序),我们实际上应该等到它执行完成后再继续执行index.js.

所以,总而言之,background.js应该是这样的:

browser.browserAction.onClicked.addListener(async ()=>{
   await browser.tabs.create({url: 'index.html'});
   await browser.tabs.executeScript({file: "vue.js"});
   await browser.tabs.executeScript({file: "index.js"});
});

并删除

    <script src="vue.js"></script>
    <script src="index.js"></script>

index.html


推荐阅读