Ошибка vue is not a constructor

I using webpack, after build and run in chrome show this error,I don’t know how to solve it.

My code is very simple:

enter image description here

enter image description here

enter image description here

{
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-runtime": "5",
    "css-loader": "^0.26.1",
    "html-webpack-plugin": "^2.28.0",
    "vue-hot-reload-api": "^2.0.9",
    "vue-html-loader": "^1.2.3",
    "vue-loader": "10.0.3",
    "vue-style-loader": "^2.0.0",
    "vue-template-compiler": "^2.1.10",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  },
  "dependencies": {
    "vue": "^2.1.10"
  }
}

Do you want to know how to solve Uncaught typeerror: vue is not a constructor?

Read this article for you to understand this error and know how to fix it.

Through this article, you will understand what Uncaught typeerror: vue is not a constructor means, How and why this error occurs, and know the different steps to solve it.

So first, let us know what this error means.

The Uncaught typeerror: vue is not a constructor is an error message that appears in the browser console when you are trying to create a new instance of Vue but it fails because Vue is not recognized as a constructor function.

This error message can occur due to various reasons.

But Before that, let’s discuss a few of the key terms that can be found in this error message.

We’ll talk about the concepts of Uncought typeerror, and vue.

What is Uncaught TypeError?

“Uncaught TypeError” is an error message that appears in the browser console when a JavaScript function or operation is attempted on a value that is not of the expected type.

What is vue?

Vue, also known as Vue.js, is a progressive JavaScript framework used for building user interfaces (UIs) and single-page applications.

It was created by Evan You and released in 2014 as an open-source project.

Now let’s proceed to the reasons why Uncaught typeerror: vue is not a constructor occurs.

Why does Uncaught typeerror: vue is not a constructor occur?

“Uncaught typeerror: vue is not a constructor” error occurs when there is an issue with the Vue.js library or its initialization in your code.

This error can occur for a number of reasons, such as:

  1. A variable or object is not properly defined or initialized.
  2. A function is being called with the wrong number or type of argument.
  3. An incorrect data type is being used in an operation.

1. A variable or object is not properly defined or initialized:

If a variable or object is not properly defined or initialized in your code, it can result in an “Uncaught TypeError: Vue is not a constructor” error when attempting to create a new instance of Vue.

For example, let’s say you have defined a variable named “myApp” in your code and you want to create a new Vue instance using this variable as the root element:

var myApp = document.getElementById('app');
var app = new Vue({
  el: myApp,
  data: {
    message: 'Hello Vue!'
  }
})

However, if the variable “myApp” is not properly defined or initialized, this can result in an error message:

Uncaught TypeError: Vue is not a constructor

2. A function is being called with the wrong number or type of argument:

If the function is called with only one argument or an argument of the wrong type, such as a number instead of a string, this can result in a type error when the Vue instance is initialized.

For example, let’s say you have defined a function named “initVue” that initializes a new Vue instance with the provided element and message:

function initVue(element, message) {
  var app = new Vue({
    el: element,
    data: {
      message: message
    }
  })
}

initVue('#app', 'Hello Vue!');

In this example, the “initVue” function takes two arguments: “element” and “message“.

If the function is called with an incorrect number or type of argument, this can result in an error message stating:

Uncaught TypeError: Vue is not a constructor

3. An incorrect data type is being used in an operation.

If a function is being called with the wrong number or type of argument, it can result in an “Uncaught TypeError: Vue is not a constructor” error when attempting to create a new instance of Vue.

For example, let’s say you have defined a variable named “appMessage” that you want to use as the message data in a new Vue instance:

var appMessage = 'Hello Vue!';
var app = new Vue({
  el: '#app',
  data: {
    message: appMessage
  }
})

In this example, we define a variable named “appMessage” to use as the message data in a new Vue instance.

if “appMessage” is null or undefined, this can result to:

Uncaught TypeError: Vue is not a constructor

When the Vue instance tries to access the “message” property.

Now let’s fix this error.

How to fix Uncaught typeerror: vue is not a constructor?

To fix the “Uncaught TypeError: Vue is not a constructor” error, you can try the following steps:

  • Solution 1: Ensure that Vue is properly loaded:

Check that the Vue library is properly loaded into your application.

You can verify this by inspecting the browser console for any errors.

Here is an example code snippet that demonstrates how to ensure that Vue is properly loaded into your application:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Define a new Vue instance
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello, world!'
      }
    });
  </script>
</body>
</html>

In this example, we include the Vue library from the CDN by adding the following script tag to our HTML head:

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

By including the Vue library from a reliable source and making sure that it is properly loaded, we can ensure that our Vue application will work as intended.

  • Solution 2: Verify that the DOM element exists:

Ensure that the DOM element referenced in your Vue instance exists on the page.

Here’s an example code snippet that demonstrates how to verify that the DOM element exists before creating a new Vue instance:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Verify that the #app element exists
    if (document.getElementById('app')) {
      // Define a new Vue instance
      var app = new Vue({
        el: '#app',
        data: {
          message: 'Hello, world!'
        }
      });
    } else {
      console.error('The #app element does not exist.');
    }
  </script>
</body>
</html>

In this example, we first verify that the #app element exists using the document.getElementById method.

If the element exists, we define a new Vue instance and set the el property to the #app element.

If the element does not exist, we log an error message to the console.

  • Solution 3: Verify that the correct data type is being used:

Ensure that the correct data type is being used in the operation.

For example, if you are passing arguments to a function, verify that the correct data type and number of arguments are being used.

Here’s an example code snippet that demonstrates how to verify that the correct data type is being used in a Vue component:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Define a new Vue component
    Vue.component('my-component', {
      props: {
        count: Number
      },
      template: `
        <div>
          <p>The count is: {{ count }}</p>
        </div>
      `
    });

    // Define a new Vue instance
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello, world!',
        count: 0
      },
      methods: {
        incrementCount() {
          // Verify that count is a number before incrementing
          if (typeof this.count === 'number') {
            this.count++;
          } else {
            console.error('The count is not a number.');
          }
        }
      }
    });
  </script>
</body>
</html>

In this example, we define a new Vue component that takes a count prop of type Number.

We then define a new Vue instance with a count data property of type Number, along with a method called incrementCount that checks that count is a number before incrementing it.

  • Solution 4: Update to the latest version of Vue:

If you are using an outdated version of Vue, upgrading to the latest version may resolve any issues that are causing the error.

To see which dependencies need updating you can run this to your terminal or command:

npm outdated

To update the Vue package to the latest version you run this code to your terminal or command:

npm update vue

If your project depends on other packages that have updates available, you can update them by running

this code to your terminal or command:

npm update

So those are the alternative solutions that you can use to fix “Uncaught typeerror: vue is not a constructor”.

Hoping that one or more of them helps you troubleshoot your error.

Here are the other fixed Python errors that you can visit, you might encounter them in the future.

  • typeerror unsupported operand type s for str and int
  • typeerror: object of type int64 is not json serializable
  • typeerror: bad operand type for unary -: str

Conclusion

To conclude, the “Uncaught typeerror: vue is not a constructor” is an error message that occurs when there is an issue with the Vue.js library or its initialization in your code.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding the Error.

We’re happy to help you.

Happy coding! Have a Good day and God bless.

Version

2.2.6

Reproduction link

Steps to reproduce

I was using Vue 2.1.8 with webpack2 and loading vue in my backbone router with require.ensure function provided by webpack for code splitting.

require.ensure([], function(){
            window.Vue = require('vue');
});

This allowed be to load Vue library only for the routes I needed, but since I’ve updated to 2.2.6 I get TypeError: Vue is not a constructor in the browser.

What is expected?

To build as before

What is actually happening?

TypeError: Vue is not a constructor


Using import Vue from 'vue' will not help since I want the Vue library to be loaded on demand. Is there any ways to achieve this.

The CLI should have created a file called main.js. In there you’ll have something a bit like this that creates a new Vue instance:

new Vue({
  render: h => h(App)
}).mount('#app')

It might use an el property instead of calling mount and it may mention store or router if you chose to include those when creating the project. It doesn’t really matter, the key thing is that this is where the root Vue instance gets created. Unless you’re writing an atypical application you shouldn’t need to use new Vue again. You certainly shouldn’t be using it inside a .vue file.

The App referenced in the code I wrote above should be the component in App.vue, which should be imported earlier in main.js.

Then there’s your App.vue. This line is a bit odd:

import App from './components/Navigation-Drawer.vue'

Technically it isn’t wrong but it’s really confusing. Rename App to some a bit more sensible, like NavigationDrawer. You’ll need to update everywhere it’s used, including the template.

Next up, Navigation-Drawer.vue. There are several problems here.

Firstly, get rid of the id="app" on the template, that just shouldn’t be there and may cause problems.

To implement onclick="openNav()" in Vue you’d instead write @click="openNav" and then define openNav within the methods section of the component.

The script section should look something like this:

<script>
    export default {
        name: 'NavigationDrawer',

        props: {
            msg: String
        },

        // Note that this is a function when used on a component
        data () {
            return {
                name1: 'name 1',
                name2: 'name 2',
                name3: 'name 3',
                name4: 'name 4'
            }
        },

        methods: {
            openNav() {
                console.log('openNav called')
            },

            closeNav() {
                console.log('closeNav')
            }
        }
    }
</script>

Hopefully that’ll be enough to get it all working.

The original linting errors were caused because:

  1. You were creating a variable called app but never using it.
  2. You were trying to call new Vue but hadn’t imported Vue. In general you need to import things if you want to be able to access them from inside a .vue file.

However, the linting errors were just side-effects of the more serious problems I’ve outlined above.

Do you want to know how to solve Uncaught typeerror: vue is not a constructor?

Read this article for you to understand this error and know how to fix it.

Through this article, you will understand what Uncaught typeerror: vue is not a constructor means, How and why this error occurs, and know the different steps to solve it.

So first, let us know what this error means.

The Uncaught typeerror: vue is not a constructor is an error message that appears in the browser console when you are trying to create a new instance of Vue but it fails because Vue is not recognized as a constructor function.

This error message can occur due to various reasons.

But Before that, let’s discuss a few of the key terms that can be found in this error message.

We’ll talk about the concepts of Uncought typeerror, and vue.

What is Uncaught TypeError?

“Uncaught TypeError” is an error message that appears in the browser console when a JavaScript function or operation is attempted on a value that is not of the expected type.

What is vue?

Vue, also known as Vue.js, is a progressive JavaScript framework used for building user interfaces (UIs) and single-page applications.

It was created by Evan You and released in 2014 as an open-source project.

Now let’s proceed to the reasons why Uncaught typeerror: vue is not a constructor occurs.

Why does Uncaught typeerror: vue is not a constructor occur?

“Uncaught typeerror: vue is not a constructor” error occurs when there is an issue with the Vue.js library or its initialization in your code.

This error can occur for a number of reasons, such as:

  1. A variable or object is not properly defined or initialized.
  2. A function is being called with the wrong number or type of argument.
  3. An incorrect data type is being used in an operation.

1. A variable or object is not properly defined or initialized:

If a variable or object is not properly defined or initialized in your code, it can result in an “Uncaught TypeError: Vue is not a constructor” error when attempting to create a new instance of Vue.

For example, let’s say you have defined a variable named “myApp” in your code and you want to create a new Vue instance using this variable as the root element:

var myApp = document.getElementById('app');
var app = new Vue({
  el: myApp,
  data: {
    message: 'Hello Vue!'
  }
})

However, if the variable “myApp” is not properly defined or initialized, this can result in an error message:

Uncaught TypeError: Vue is not a constructor

2. A function is being called with the wrong number or type of argument:

If the function is called with only one argument or an argument of the wrong type, such as a number instead of a string, this can result in a type error when the Vue instance is initialized.

For example, let’s say you have defined a function named “initVue” that initializes a new Vue instance with the provided element and message:

function initVue(element, message) {
  var app = new Vue({
    el: element,
    data: {
      message: message
    }
  })
}

initVue('#app', 'Hello Vue!');

In this example, the “initVue” function takes two arguments: “element” and “message“.

If the function is called with an incorrect number or type of argument, this can result in an error message stating:

Uncaught TypeError: Vue is not a constructor

3. An incorrect data type is being used in an operation.

If a function is being called with the wrong number or type of argument, it can result in an “Uncaught TypeError: Vue is not a constructor” error when attempting to create a new instance of Vue.

For example, let’s say you have defined a variable named “appMessage” that you want to use as the message data in a new Vue instance:

var appMessage = 'Hello Vue!';
var app = new Vue({
  el: '#app',
  data: {
    message: appMessage
  }
})

In this example, we define a variable named “appMessage” to use as the message data in a new Vue instance.

if “appMessage” is null or undefined, this can result to:

Uncaught TypeError: Vue is not a constructor

When the Vue instance tries to access the “message” property.

Now let’s fix this error.

How to fix Uncaught typeerror: vue is not a constructor?

To fix the “Uncaught TypeError: Vue is not a constructor” error, you can try the following steps:

  • Solution 1: Ensure that Vue is properly loaded:

Check that the Vue library is properly loaded into your application.

You can verify this by inspecting the browser console for any errors.

Here is an example code snippet that demonstrates how to ensure that Vue is properly loaded into your application:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Define a new Vue instance
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello, world!'
      }
    });
  </script>
</body>
</html>

In this example, we include the Vue library from the CDN by adding the following script tag to our HTML head:

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

By including the Vue library from a reliable source and making sure that it is properly loaded, we can ensure that our Vue application will work as intended.

  • Solution 2: Verify that the DOM element exists:

Ensure that the DOM element referenced in your Vue instance exists on the page.

Here’s an example code snippet that demonstrates how to verify that the DOM element exists before creating a new Vue instance:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Verify that the #app element exists
    if (document.getElementById('app')) {
      // Define a new Vue instance
      var app = new Vue({
        el: '#app',
        data: {
          message: 'Hello, world!'
        }
      });
    } else {
      console.error('The #app element does not exist.');
    }
  </script>
</body>
</html>

In this example, we first verify that the #app element exists using the document.getElementById method.

If the element exists, we define a new Vue instance and set the el property to the #app element.

If the element does not exist, we log an error message to the console.

  • Solution 3: Verify that the correct data type is being used:

Ensure that the correct data type is being used in the operation.

For example, if you are passing arguments to a function, verify that the correct data type and number of arguments are being used.

Here’s an example code snippet that demonstrates how to verify that the correct data type is being used in a Vue component:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    // Define a new Vue component
    Vue.component('my-component', {
      props: {
        count: Number
      },
      template: `
        <div>
          <p>The count is: {{ count }}</p>
        </div>
      `
    });

    // Define a new Vue instance
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello, world!',
        count: 0
      },
      methods: {
        incrementCount() {
          // Verify that count is a number before incrementing
          if (typeof this.count === 'number') {
            this.count++;
          } else {
            console.error('The count is not a number.');
          }
        }
      }
    });
  </script>
</body>
</html>

In this example, we define a new Vue component that takes a count prop of type Number.

We then define a new Vue instance with a count data property of type Number, along with a method called incrementCount that checks that count is a number before incrementing it.

  • Solution 4: Update to the latest version of Vue:

If you are using an outdated version of Vue, upgrading to the latest version may resolve any issues that are causing the error.

To see which dependencies need updating you can run this to your terminal or command:

npm outdated

To update the Vue package to the latest version you run this code to your terminal or command:

npm update vue

If your project depends on other packages that have updates available, you can update them by running

this code to your terminal or command:

npm update

So those are the alternative solutions that you can use to fix “Uncaught typeerror: vue is not a constructor”.

Hoping that one or more of them helps you troubleshoot your error.

Here are the other fixed Python errors that you can visit, you might encounter them in the future.

  • typeerror unsupported operand type s for str and int
  • typeerror: object of type int64 is not json serializable
  • typeerror: bad operand type for unary -: str

Conclusion

To conclude, the “Uncaught typeerror: vue is not a constructor” is an error message that occurs when there is an issue with the Vue.js library or its initialization in your code.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding the Error.

We’re happy to help you.

Happy coding! Have a Good day and God bless.

The CLI should have created a file called main.js. In there you’ll have something a bit like this that creates a new Vue instance:

new Vue({
  render: h => h(App)
}).mount('#app')

It might use an el property instead of calling mount and it may mention store or router if you chose to include those when creating the project. It doesn’t really matter, the key thing is that this is where the root Vue instance gets created. Unless you’re writing an atypical application you shouldn’t need to use new Vue again. You certainly shouldn’t be using it inside a .vue file.

The App referenced in the code I wrote above should be the component in App.vue, which should be imported earlier in main.js.

Then there’s your App.vue. This line is a bit odd:

import App from './components/Navigation-Drawer.vue'

Technically it isn’t wrong but it’s really confusing. Rename App to some a bit more sensible, like NavigationDrawer. You’ll need to update everywhere it’s used, including the template.

Next up, Navigation-Drawer.vue. There are several problems here.

Firstly, get rid of the id="app" on the template, that just shouldn’t be there and may cause problems.

To implement onclick="openNav()" in Vue you’d instead write @click="openNav" and then define openNav within the methods section of the component.

The script section should look something like this:

<script>
    export default {
        name: 'NavigationDrawer',

        props: {
            msg: String
        },

        // Note that this is a function when used on a component
        data () {
            return {
                name1: 'name 1',
                name2: 'name 2',
                name3: 'name 3',
                name4: 'name 4'
            }
        },

        methods: {
            openNav() {
                console.log('openNav called')
            },

            closeNav() {
                console.log('closeNav')
            }
        }
    }
</script>

Hopefully that’ll be enough to get it all working.

The original linting errors were caused because:

  1. You were creating a variable called app but never using it.
  2. You were trying to call new Vue but hadn’t imported Vue. In general you need to import things if you want to be able to access them from inside a .vue file.

However, the linting errors were just side-effects of the more serious problems I’ve outlined above.

**»10:7 error ‘app’ is assigned a value but never used no-unused-vars»
I know there is some similar question due this. But I dont know why my code doesnt work at all.

So the error is at the main.js file line 10.
I thought I’m using my «app» with el:’app’ or in export fault with ‘app’

I have 2 files

**App.vue:****






    <template>
      <div id="app" v-cloack>
        <img src="./assets/999.jpg">
        <h1>{{ msg }}</h1>
        <ul>
          <input type="file" ref="myFile" @change="selectedFile"><br/>
          <textarea v-model="text"></textarea>
      </div>
    </template>


    <script>
    //import HelloWorld from './components/HelloWorld';
    //import main from './main.js';
    export default {
      name: 'app',
      data: ()=> {
        //
          return{
              msg: 'Datei uploaden'

          }
      },
    }
    </script>

    <style>

    </style>'''





**main.js:**




    import Vue from 'vue'
    import App from './App.vue'
    import vuetify from './plugins/vuetify';

    Vue.config.productionTip = false
    Vue.config.devtools = false;
    export default {
      name: 'app',
      data: ()=> {
      var app;
      app =new Vue({

    el: '#app',
    vuetify,
    render: h => h(App),
    data: {
      text:''
    },

    methods:{
        selectedFile() {
          console.log('selected a file');
          console.log(this.$refs.myFile.files[0]);

          let file = this.$refs.myFile.files[0];
          if(!file || file.type !== 'text/plain') return;

          // Credit: https://stackoverflow.com/a/754398/52160
          let reader = new FileReader();
          reader.readAsText(file, "UTF-8");
          reader.onload =  evt => {
            this.text = evt.target.result;
          }
          reader.onerror = evt => {
            console.error(evt);
          }

        }
    }
  })
  }
}
//.$mount('#app')

I really struggle since a few days. I would be very happy if anybody can help
Thanks

asked Apr 15, 2020 at 18:48

GEK's user avatar

1

You can add /* exported variableName */ to ignore the eslint since you are using app variable outside your file

so above your app variable add /* exported app */

to read more https://eslint.org/docs/rules/no-unused-vars

Change main.js to this code

import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';

Vue.config.productionTip = false;
Vue.config.devtools = false;

var app = new Vue({
    el: '#app',
    vuetify,
    render: h => h(App),
    data: {
        text: ''
    },
    methods: {
        selectedFile() {
            console.log('selected a file');
            console.log(this.$refs.myFile.files[0]);

            let file = this.$refs.myFile.files[0];
            if (!file || file.type !== 'text/plain') return;

            // Credit: https://stackoverflow.com/a/754398/52160
            let reader = new FileReader();
            reader.readAsText(file, "UTF-8");
            reader.onload = evt => {
                this.text = evt.target.result;
            }
            reader.onerror = evt => {
                console.error(evt);
            }

        }
    }
})

export default app

answered Apr 15, 2020 at 18:58

Quantumass's user avatar

QuantumassQuantumass

8066 silver badges11 bronze badges

Банальный пример
{{ message }} (в дивах с id="app")

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

Не работает из за конфликта (я так понимаю конфликт в виде переменной {{ message }}) vue и laravel, как это исправить?


  • Вопрос задан

    более трёх лет назад

  • 425 просмотров

Пригласить эксперта

{
data:{…},
…,
delimiters:[«[[«,»]]»]
}

Или можете добавить @ перед vue переменной, но на самом деле это все извращения.

Используйте vue компоненты и vue template в нем, передавая нужные переменные в компоненты через props или api.


  • Показать ещё
    Загружается…

29 янв. 2023, в 03:07

300000 руб./за проект

29 янв. 2023, в 02:16

700000 руб./за проект

29 янв. 2023, в 01:54

5000 руб./за проект

Минуточку внимания

Логотип Vue
Vue.js

  • Обучение

    • Документация

      • Руководство
      • API
      • Рекомендации
      • Примеры
      • Книга рецептов
    • Видео курсы

      • Vue Mastery

      • Vue School

  • Экосистема

    • Помощь

      • Форум
      • Чат
      • Митапы
    • Инструментарий

      • Инструменты разработчика
      • Vue CLI
      • Vue Loader
    • Официальные плагины

      • Vue Router
      • Vuex
      • Vue Server Renderer
    • Новости

      • Еженедельные новости
      • Roadmap
      • События
      • Twitter
      • Блог
      • Вакансии
      • Сообщество разработчиков
  • Команда
  • Ресурсы

    • Партнёры
    • Темы
    • Awesome Vue
    • Найти пакеты для Vue
  • Поддержать Vue

    • Единоразовые пожертвования
    • Повторяющиеся взносы
    • Магазин футболок
  • Переводы

    • English
    • 中文
    • 日本語
    • 한국어
    • Português
    • Français
    • Tiếng Việt
    • Español
    • Bahasa Indonesia

Эта документация для версий v2.x и ранее.
Для v3.x, документация на русском здесь.

Каждое приложение начинается с создания нового экземпляра Vue с помощью функции Vue:

var vm = new Vue({
// опции
})

Хоть Vue и не реализует паттерн MVVM в полной мере, архитектура фреймворка им во многом вдохновлена. Поэтому переменную с экземпляром Vue традиционно именуют vm (сокращённо от ViewModel).

При создании экземпляра Vue необходимо передать объект опций. Большая часть этого руководства посвящена описанию, как можно использовать эти опции для достижения желаемого поведения. Полный список опций можно посмотреть в справочнике API.

Приложение Vue состоит из корневого экземпляра Vue, создаваемого с помощью new Vue, опционально организованного в дерево вложенных, повторно используемых компонентов. Например, дерево компонентов для приложения TODO-списка может выглядеть так:

Корневой экземпляр
└─ TodoList
├─ TodoItem
│ ├─ TodoButtonDelete
│ └─ TodoButtonEdit
└─ TodoListFooter
├─ TodosButtonClear
└─ TodoListStatistics

Подробнее о системе компонентов мы поговорим позднее. А сейчас запомните, что все компоненты Vue также являются экземплярами Vue и поэтому принимают такой же объект опций (за исключением нескольких специфичных для корневого).

Данные и методы

Когда экземпляр Vue создан, он добавляет все свойства, найденные в опции data, в систему реактивности Vue. Поэтому представление будет «реагировать» на их изменения, обновляясь в соответствии с новыми значениями.

// Наш объект data
var data = { a: 1 }

// Объект добавляется в экземпляр Vue
var vm = new Vue({
data: data
})

// Получение свойства из экземпляра
// возвращает то же значение из исходных данных
vm.a === data.a // => true

// Изменение свойства экземпляра
// влияет на оригинальные данные
vm.a = 2
data.a // => 2

// ... и наоборот
data.a = 3
vm.a // => 3

Когда значения изменяются, представление будет переотрисовано. Но обратите внимание, свойства в data будут реактивными, только если они существовали при создании экземпляра. Это значит, если добавить новое свойство, например:

То изменения в b не будут вызывать никаких обновлений. Если вы знаете, что свойство вам понадобится позже, но изначально оно пустое или несуществующее, нужно просто установить начальное значение. Например:

data: {
newTodoText: '',
visitCount: 0,
hideCompletedTodos: false,
todos: [],
error: null
}

Единственным исключением здесь является использование Object.freeze(), который предотвращает изменение существующих свойств, что также означает невозможность отслеживать изменения системой реактивности.

var obj = {
foo: 'bar'
}

Object.freeze(obj)

new Vue({
el: '#app',
data: obj
})

<div id="app">
<p>{{ foo }}</p>
<!-- мы теперь не можем обновить `foo`! -->
<button v-on:click="foo = 'baz'">Изменить</button>
</div>

Кроме свойств объекта data, экземпляры Vue предоставляют ряд служебных свойств и методов экземпляра. Их имена начинаются с префикса $, чтобы отличаться от пользовательских свойств. Например:

var data = { a: 1 }
var vm = new Vue({
el: '#example',
data: data
})

vm.$data === data // => true
vm.$el === document.getElementById('example') // => true

// $watch — это метод экземпляра
vm.$watch('a', function (newValue, oldValue) {
// Этот коллбэк будет вызван, когда изменится `vm.a`
})

С полным списком свойств и методов экземпляра Vue можно ознакомиться в справочнике API.

Хуки жизненного цикла экземпляра

Каждый экземпляр Vue при создании проходит через последовательность шагов инициализации — например, настраивает наблюдение за данными, компилирует шаблон, монтирует экземпляр в DOM, обновляет DOM при изменении данных. Между этими шагами вызываются функции, называемые хуками жизненного цикла, с помощью которых можно выполнять свой код на определённых этапах.

Например, хук created можно использовать для выполнения кода после создания экземпляра:

new Vue({
data: {
a: 1
},
created: function () {
// `this` указывает на экземпляр vm
console.log('Значение a: ' + this.a)
}
})
// => "Значение a: 1"

Существуют и другие хуки, вызываемые на различных стадиях жизненного цикла экземпляра, например mounted, updated и destroyed. Все хуки вызываются с контекстной переменной this, ссылающейся на вызывающий экземпляр Vue.

Не используйте стрелочные функции в свойствах экземпляра и в коллбэках, например created: () => console.log(this.a) или vm.$watch('a', newVal => this.myMethod()). Так как стрелочные функции не имеют собственного this, то this в коде будет обрабатываться как любая другая переменная и её поиск будет производиться в областях видимости выше до тех пор пока не будет найдена, часто приводя к таким ошибкам, как Uncaught TypeError: Cannot read property of undefined или Uncaught TypeError: this.myMethod is not a function.

Диаграмма жизненного цикла

Ниже представлена диаграмма жизненного цикла экземпляра. Необязательно понимать её полностью прямо сейчас, но по мере изучения и практики разработки к ней полезно будет обращаться.

Жизненный цикл экземпляра Vue

Project scenario:

Today, in the process of reviewing the basis of Vue, I tried to introduce and use Vue with traditional HTML and native memory, and then found that I really pulled it. The memory is not only vague, but also confused. Vue2 mixed with vue3 is there! Next, let’s see how to report the error.

Problem Description:

The HTML structure is as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script>
    const app = Vue.createApp({
        data() {
            return {
                message: '666'
            }
        },
        template: "<h2>{{message}}</h2>"
    })
    app.mount("#app")
  </script>
</html>

Good guy, 666 didn’t render. Just click and report me the error
Uncaught TypeError: Vue.createApp is not a function。
I’m still wondering. I think it’s ok if createapp creates a Vue application and mount it to the node?Why, vue.createapp is not available yet

Cause analysis:

Later, I read the document and found that I had mixed up vue.createapp and mount, which are the writing methods of vue3, but I introduced vue2
it is clearly written on the official website. Vue2 uses new and is an EL mount node
vue2 is written as follows:

 var app = new Vue({
   el: '#app',
   data: {
     message: '666',
   },
   template: '<h2>{{message}}</h2>',
});

The following is the way vue3 is written

 const app = Vue.createApp({
     data() {
         return {
             message: '666'
         }
     },
     template: "<h2>{{message}}</h2>"
 })
 app.mount("#app")

Read More:

Я работаю с Vue.js, и он по какой-то причине просто перестал работать. Кажется, я не могу найти свою ошибку — смотрел на нее часами.

Это мой HTML-файл — просто зависимости и таблица, отображающая данные в users.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello, world!</title>
    </head>
    <body>
        <script
            src = "https://code.jquery.com/jquery-3.3.1.min.js"
            type = "text/javascript">
        </script>
        <link 
            href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
            rel = "stylesheet" 
        >
        <script
            src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            type = "text/javascript">
        </script>
        <script
            src = "https://cdn.jsdelivr.net/npm/vue"
            type = "text/javascript">
        </script>

        <script src = "/js/app.js" type = "text/javascript"></script>

        <div class = "container">
            <div id = "app">
                <table class = "table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Personal Number</th>
                            <th>Volcano Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for = "user in users">
                            <td><% user.name %></td>
                            <td><% user.personal_number %></td>
                            <td><% user.volcano_amount %></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </body>
</html>

И это файл app.js, который просто запускает экземпляр Vue, создает массив users и выполняет запрос AJAX, который обновляет массив users.

var app = new Vue({
    el: '#app',
    data: {
        users: []
    },
    mounted: function() {
        var vue_object = this;
        $.getJSON('users', function(data) {
            vue_object.users = data;
        });
    },
    delimiters: ['<%', '%>']
});

Результат крайне неутешительный — все в простом HTML. В таблице 2 строки — заголовок и строка с <% user.xxx %>, как будто Vue не существует.

Я предполагаю, что это означает, что что-то не работает, хотя сам app.js запускается (я пробовал добавить console.info, и он распечатал)

Надеюсь, у вас есть хорошие идеи

В настоящее время я пытаюсь создать компонент Vue.js. Когда я запускаю приложение, появляется ошибка. Сообщение об ошибке, как показано ниже:

enter image description here

<template>
    <div class="hello" id="app">
         <span style="font-size:30px;cursor:pointer;" onclick="openNav()">☰</span>

        <div id="mySidenav" class="sidenav">
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
            <a href="#">{{name1}}</a>
            <a href="#">{{name2}}</a>
            <a href="#">{{name3}}</a>
            <a href="#">{{name4}}</a>

            <div id="bottom">
                <input v-model="name1" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name2" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name3" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name4" style="margin-left: 25px;max-width: 50%;">
            </div>

        </div>
        <h2>Lorem ipsum dolor sit amet</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elit velit, dictum in urna et,
            vulputate ornare sapien. Phasellus sed metus sed dolor hendrerit iaculis.
            Cras eget libero sit amet massa aliquet dignissim. Vivamus faucibus lorem sit amet semper luctus.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In at placerat
            felis,
            id finibus mauris. Proin maximus orci quis lacus pellentesque, ac dignissim sapien vestibulum. Maecenas
            pharetra
            vulputate semper.
            Suspendisse potenti. Donec nisi nisi, aliquam eget felis euismod, semper dictum ligula.
            Aenean mauris enim, iaculis vel malesuada vel, pulvinar et risus. Fusce sit amet orci eget diam commodo
            ultricies sed vel elit.
            Curabitur quis scelerisque est.</p>
    </div>
</template>

<script>
    //Vue App
    var app = new Vue({
        el: '#app',
        data: {
            /*
            navlink: [
                {id: 1, link: "https://www.tfbern.ch"}, 
                {id: 2, link: "https://www.tfbern.ch"},
                {id: 3, link: "https://www.tfbern.ch"},
                {id: 4, link: "https://www.tfbern.ch"}
                ]
            */

            name1: 'name 1',
            name2: 'name 2',
            name3: 'name 3',
            name4: 'name 4'
        }
    })
    export default {
        name: 'NavigationDrawer',
        props: {
            msg: String
        }
    }

    //Navbar Animation
   /* 
   function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
    }

    function closeNav() {
        document.getElementById("mySidenav").style.width = "0"; -->
    }
     */
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

Навигационно- Drawer.vue


<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <App msg="test">
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import App from './components/Navigation-Drawer.vue'
export default {
  name: 'App',
  components: {
    HelloWorld,
    App
  }
}

</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

App.vue

2 ответа

Лучший ответ

Это ошибки от Eslint. См. https://eslint.org/docs/rules/no-unused-vars и https://eslint.org/docs/rules/no-undef для деталей.

Чтобы удалить эти ошибки, добавьте эту строку непосредственно перед строкой, в которой вы инициализируете приложение.

    // eslint-disable-next-line
    var app = new Vue({ 
    // rest of the code 

Убедитесь, что строка с eslint-disable-next-line закомментирована. Это скажет эслинту игнорировать эту строку, а не задерживать ее.


1

Albert Pinto
17 Фев 2020 в 10:28

CLI должен был создать файл с именем main.js. Там у вас будет что-то вроде этого, создающее новый экземпляр Vue:

new Vue({
  render: h => h(App)
}).mount('#app')

Он может использовать свойство el вместо вызова mount и может упоминать store или router, если вы решили включить их при создании проекта. Это не имеет значения, главное, что именно здесь создается корневой экземпляр Vue. Если вы не пишете нетипичное приложение, вам не нужно использовать new Vue снова. Вы, конечно, не должны использовать его внутри .vue файла.

App, указанный в коде, который я написал выше, должен быть компонентом App.vue, который должен быть импортирован ранее в main.js.

Тогда есть твой App.vue. Эта строка немного странная:

import App from './components/Navigation-Drawer.vue'

Технически это не так, но это действительно сбивает с толку. Переименуйте App в более разумное, например, NavigationDrawer. Вам нужно будет обновлять везде, где он используется, включая шаблон.

Далее Navigation-Drawer.vue. Здесь есть несколько проблем.

Во-первых, избавьтесь от id="app" в шаблоне, который просто не должен присутствовать и может вызвать проблемы.

Чтобы реализовать onclick="openNav()" в Vue, вместо этого вы должны написать @click="openNav", а затем определить openNav в разделе methods компонента.

Секция скрипта должна выглядеть примерно так:

<script>
    export default {
        name: 'NavigationDrawer',

        props: {
            msg: String
        },

        // Note that this is a function when used on a component
        data () {
            return {
                name1: 'name 1',
                name2: 'name 2',
                name3: 'name 3',
                name4: 'name 4'
            }
        },

        methods: {
            openNav() {
                console.log('openNav called')
            },

            closeNav() {
                console.log('closeNav')
            }
        }
    }
</script>

Надеюсь, этого будет достаточно, чтобы все заработало.

Первоначальные ошибки распечатки были вызваны тем, что:

  1. Вы создавали переменную с именем app, но никогда не использовали ее.
  2. Вы пытались позвонить new Vue, но не импортировали Vue. В общем, вам нужно импортировать вещи, если вы хотите иметь доступ к ним из файла .vue.

Однако ошибки в связывании были лишь побочными эффектами более серьезных проблем, которые я изложил выше.


0

skirtle
19 Фев 2020 в 15:23

I got the same error. I declared metadata as @leonardovilarinho suggested, but it still get the same error.

Here is my router:

var router = new VueRouter({
    mode: 'history',
    base: '/account/',
    linkActiveClass: 'active',
    meta: {
        permission: 'any',
        fail: '/',
    },
    routes: [
        {
            path: '/contribution',
            component: contribution,
            meta: {
                permission: 'any',
                fail: '/',
            },
        },
        {
            path: '/deposits',
            component: deposits,
            meta: {
                permission: 'any',
                fail: '/',
            },
        },
        {
            path: '/withdraw',
            component: withdraw,
            meta: {
                permission: 'any',
                fail: '/',
            },
        },
        {
            path: '/settings',
            component: settings,
            meta: {
                permission: 'any',
                fail: '/',
            },
        }
    ]
});

And this is how I add it:

var app = new Vue({
    el: '#app',
    router: router,
    ......

Any ideas?

#javascript #vue.js #vuejs2

Вопрос:

Я пытаюсь начать использовать vue.js и возникли проблемы с его настройкой. В моем пакете.json я установил последнюю версию "vue": "^2.6.14", , и в моей main.js папке я включил вот так

 import Vue from "vue";
var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    }
  })
 

и в свой html-файл я добавил это:

 <div id="app">
  {{ message }}
</div>
 

когда webpack компилируется, он создает это main.js файл, но {{ сообщение }} не изменен на Hello Vue!. Что я здесь делаю не так, что это не работает?

Также в инструментах разработки не отображается ошибка.

Комментарии:

1. возможно, вам захочется переместить свойство данных и шаблон= {{message}} в App.vue вместо main.js и index.html .

2. Проверьте консоль инструментов разработки вашего браузера на наличие ошибок

3. @Фил спасибо, но никакой ошибки там нет

4. Вам придется пройти все шаги, которые вы предпринимаете… как вы начали проект? Вы используете Vue CLI? Какие команды вы используете для запуска или создания своего проекта? Какой адрес вы открываете в своем браузере?

5. Как вы можете видеть здесь , ваш код работает просто отлично

Ответ №1:

Попробуй

 import Vue from "vue";
var app = new Vue({
    el: '#app',
    data () {
      return {
        message: "Hello Vue!"
      }
    }
  }).$mount('#app');
 

Это решило бы вашу проблему

Комментарии:

1. где бы я это добавил? до конца файла?

2. Я отредактировал свой ответ, вам нужно заменить объект данных для работы

Ответ №2:

 import Vue from "vue";

new Vue({
   data() {
       return {
          message: 'Hello Vue!',
       };
   },
}).$mount('#app');
 

Комментарии:

1. к сожалению, по-прежнему ничего не показывает, я также добавил window.Vue = Vue; , но ничего не отображается

2. Вы уверены, что включаете файл js в свой html..

3. да, я проверил исходный код и main.js загружено — это тот контент, который я опубликовал в вопросе.

4. Да, братан, ты не включил свой js-файл в html. работает нормально. codepen.io/pen/?editors=1111

Solution 1

Vue is the default export from that library so you import like this.

import Vue from 'vue'

Solution 2

You need to import the runtime only build. This comment in the Github issues explains.

Put this in your webpack.config.js.

resolve: {
  alias: {
    vue: 'vue/dist/vue.js'
  }
}

Related videos on Youtube

ESLint Quickstart - find errors automatically

08 : 52

ESLint Quickstart — find errors automatically

Top 8 Ways To Create A Vue.js App In 2021

16 : 09

Top 8 Ways To Create A Vue.js App In 2021

Simple Frontend Pagination | React

19 : 13

Simple Frontend Pagination | React

Vue JS 3 Tutorial for Beginners #8 - The Vue Router

47 : 48

Vue JS 3 Tutorial for Beginners #8 — The Vue Router

7.4: The Constructor Function in JavaScript - p5.js Tutorial

12 : 39

7.4: The Constructor Function in JavaScript — p5.js Tutorial

JavaScript : TypeError: CleanwebpackPlugin is not a constructor

01 : 44

JavaScript : TypeError: CleanwebpackPlugin is not a constructor

Object constructor

13 : 39

Every New Vue Developer Has Made These Mistakes...

18 : 04

Every New Vue Developer Has Made These Mistakes…

Vue JS 3 tutorial #2 How to use VueJs with CDN

09 : 16

Vue JS 3 tutorial #2 How to use VueJs with CDN

Property '…' has no initializer and is not definitely assigned in the constructor

00 : 25

Property ‘…’ has no initializer and is not definitely assigned in the constructor

08 - How to Disable Eslint in VS Code for JavaScript Projects

03 : 53

08 — How to Disable Eslint in VS Code for JavaScript Projects

Node.js Class is not a constructor - NodeJS

01 : 16

Node.js Class is not a constructor — NodeJS

Comments

  • I using webpack, after build and run in chrome show this error,I don’t know how to solve it.

    My code is very simple:

    enter image description here

    enter image description here

    enter image description here

    {
      "devDependencies": {
        "babel-core": "^6.23.1",
        "babel-loader": "^6.3.2",
        "babel-plugin-transform-runtime": "^6.23.0",
        "babel-preset-es2015": "^6.22.0",
        "babel-runtime": "5",
        "css-loader": "^0.26.1",
        "html-webpack-plugin": "^2.28.0",
        "vue-hot-reload-api": "^2.0.9",
        "vue-html-loader": "^1.2.3",
        "vue-loader": "10.0.3",
        "vue-style-loader": "^2.0.0",
        "vue-template-compiler": "^2.1.10",
        "webpack": "^2.2.1",
        "webpack-dev-server": "^2.4.1"
      },
      "dependencies": {
        "vue": "^2.1.10"
      }
    }
    

    • Try to import vue like this import Vue from 'vue'

  • @BelminBedak thank you, my original code is import * as Vue from 'vue'; , I change it can work.

  • I import Vue like this but it still does not work. Any idea why?

  • What can I do if I have no webpack? I only use ts-node to resolve packages.

  • @mesqueeb Use vue/dist/vue.js in development and vue/dist/vue.min.js in production.

  • it worked great, can you please why it didn’t work as window.Vue = require(‘vue’); thank you!

  • @salmanifrahim At that point it would depend on your build process, require(‘vue’) does not work in the browser and «SHOULD» be compiled to support both default and primary exports. If you add require(«vue’).default it might work, wowever, your best bet is to lean into the ESM import statement like above.

Recents

Related

  • Ошибка vts a2 fcscom
  • Ошибка vtm 4 акура мдх
  • Ошибка vtg износ масла
  • Ошибка vsvcp110 dll скачать как решить
  • Ошибка vss что это