Aseem
Aseem

Reputation: 6769

How to use Vuejs SFC (single file component) in django

fil1.vue

<script setup>
import { ref } from 'vue'

const msg = ref('Hello World!')
</script>

<template>
  <h1>{{ msg }}</h1>
  <input v-model="msg">
</template>

I would like to render this in my Django template.

Previously with normal vue components I was able to do use them as follows:

JS file:

Vue.component('comp1', {...})

django html template:

<comp1> </comp1>

Update 04-08-2022

I was able to get App.vue mounted on django div element with id=app -My github repo

If someone can provide a link to a public github repo that has used SFC with django that would be helpful.

Upvotes: 2

Views: 1534

Answers (2)

Dev Netics
Dev Netics

Reputation: 1

Use customElements and defineCustomElement in this way

import { createApp } from 'vue'
import { defineCustomElement } from 'vue'
import App from './App.vue'
import AddListing from "./components/AddListing.vue";
import EditListing from "./components/EditListing.vue";

// Add Listing form
customElements.define('add-listing', defineCustomElement(AddListing))
customElements.define('edit-listing', defineCustomElement(EditListing))

const marketApp = createApp(App)
marketApp.mount('#app')

Then you will be able to use it outside of div#app by calling:

<add-listing />

or

<edit-listing />

Upvotes: 0

Aseem
Aseem

Reputation: 6769

Following is what I know so far. There may be a better solution out there.

  • Django has its own routers and template engine. Django can render html pages on certain URLs.
  • Vue SFC has its own routers. In Vue3 SFC everything start from a single entrypoint file with id=app and from there we can route users to different pages. Everything is done in Vue. No Django needed or used.
  • So using SFC with Django is not possible or is not the correct approach.
  • We can use SFC for UI and DRF for APIs. This can be a good combination where DRF is completely independent of Vue SFC

I like Vue components and I also like Django routers and Django template engine.

Following is how I am using it currently:

  • I dont use Vue SFC but I do use Vue components. I am using Vue2.6 .
  • I have templates rendered by django. They call different Vuejs components;

component1.js

   Vue.component('name-comp', {
    props: {
          
       },
       data: function () {
           return {
          
           }
       },
       watch: {
          
       },
       mounted: async function () {
          
       },
       methods: {
         
    
       },
       template: `
    
       `,
       delimiters: ["[[", "]]"],
   });

h1.html

<name-comp></name-comp>
<script type="text/javascript" src="{% static 'app1/js/component1.js'%}">

Upvotes: 1

Related Questions