[Vuejs]-Use pure js variable in vue component

1👍

Variable visibility in the template:

<template>
  <span>{{ variableVisibleInTemplate }}</span>
</template>

<script>
export default {
  data() {
    return {
      variableVisibleInTemplate: variableVisibleInScript
    };
  }
};
</script>

Example 1:

You return exactly one variable

src/assets/bra.js

var name = "John";

module.exports = name;

src/App.vue

<template>
  <span>{{ name }}</span>
</template>

<script>
import name from "./assets/bra.js";
// or:
// const name = require("./assets/bra.js");

export default {
  data() {
    return {
      name: name
    };
  }
};
</script>

Example 2

You return many variables

src/assets/bra.js

var name = "John";

module.exports = {
  name: name
};

src/App.vue

<template>
  <span>{{ name }}</span>
</template>

<script>
import { name } from "./assets/bra.js";
// or:
// const { name } = require("./assets/bra.js");

export default {
  data() {
    return {
      name: name
    };
  }
};
</script>

Read also: Understanding module.exports and exports in Node.js

👤Gander

0👍

Simply use import/export directives.

src/assets/bra.js

export const name = "John";

src/component.vue

<script>
import { name } from "@/assets/bra";

export default {
  ...
  data() {
    return {
      name: name
    }
  }
  ...
};
</script>
👤Cue

Leave a comment